home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 July: Mac OS SDK / Dev.CD Jul 00 SDK2.toast / Development Kits / Hardware / Mac OS USB DDK / Mac OS USB DDK 1.4.1 / Examples / PrinterClassDriver / PrinterClassDriver.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-04-25  |  127.2 KB  |  3,871 lines  |  [TEXT/CWIE]

  1. /*
  2.     File:        PrinterClassDriver.c
  3.  
  4.     Contains:    MacOS USB printer class driver
  5.                 [ref. IEEE Std 1284-1994]
  6.  
  7.     Version:    xxx put version here xxx
  8.  
  9.  
  10.  
  11.     Copyright:    1998 by Apple Computer, Inc., all rights reserved.
  12.  
  13. */
  14.  
  15.  
  16. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  17.     includes
  18.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  19. #include <Gestalt.h>
  20. #include <Devices.h>
  21. #include <DriverServices.h>
  22. #include <Interrupts.h>
  23. #include <LowMem.h>
  24. #include <Folders.h>
  25. #include <String.h>
  26. #include <stdio.h>
  27. #include <USB.h>
  28.  
  29. #ifndef __CODEFRAGMENTS__
  30. #include <codefragments.h>
  31. #endif
  32.  
  33. #include "PrinterClassDriver.h"
  34. #include "TradDriverLoaderLib.h"
  35.  
  36. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  37.     constants
  38.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  39. #define MAX_SUFFIX                    127                    // maximum copies we'll enter in unit table
  40. #define kUSBParallelDrvrRsrcID        12
  41. #define kMinDrvrUnitNumber            48                    // minimum unit table entry which we'll install
  42. #define kUSS720MillisecondDelay        3*1000                // poll every three seconds
  43. #define kUSS720StatusMSDelay        100                    // poll ten times per second
  44. #define MAX_USB_TRANSFER_SIZE        TRANSFER_SIZE        // zero acts as manifest for conditional compilation
  45.  
  46. #define kUSBAttributeBulk            0x02
  47. #define kUSBInputEndpointMask        0x80
  48.  
  49. #define kDebugStatusLevel            5
  50. #define kNormalStatusLevel            4
  51.  
  52.  
  53. enum
  54. {
  55.     kUSBv12    =    0x01200000,
  56.     kUSBv135 =     0x01350000
  57. };
  58.  
  59. enum
  60. {
  61.     kCString = 0,                // StateStr, USBStatusStr selector
  62.     kPString,                    // StateStr, USBStatusStr selector
  63.     kDrvrFirstDigit = 5            // length_byte + ".USB" = 5
  64. };
  65. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  66.     manifest constants
  67. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  68. //
  69. //    DEBUGGING                        extra debugging information to USB Expert Log
  70. //    DOUBLE_BUFFER                    use a page aligned buffer in system heap to double buffer app i/o
  71. //    LOG                                echo all the write data to a log file in the system folder
  72. // LOCK_MEMORY                        LockMemory on the i/o buffer before write and unlock on write completion
  73. // VIRTUAL_MEMORY_CHECK                check the physical addresses of the buffer we pass for write requests
  74. // MACSBUG_ON_READ                    break into MacsBug before each read request
  75. //    MACSBUG_ON_READ_COMPLETE        break into MacsBug at each read completion routine
  76. //    MACSBUG_ON_WRITE                break into MacsBug on each write request
  77. // MACSBUG_ON_WRITE_COMPLETE        break into MacsBug at each write completion routine
  78. //
  79. #define DEBUGGING                        1    /* DEBUGGING */
  80. #define DOUBLE_BUFFER                    1    /* DOUBLE_BUFFER */
  81. #define LOG                                0    /* LOG */
  82. #define LOCK_MEMORY                        1    /* LOCK_MEMORY */
  83. #define MACSBUG_ON_READ                    1    /* MACSBUG_ON_READ */
  84. #define MACSBUG_ON_READ_COMPLETE        1    /* MACSBUG_ON_READ_COMPLETE */ 
  85. #define MACSBUG_ON_WRITE                1    /* MACSBUG_ON_WRITE */
  86. #define MACSBUG_ON_WRITE_COMPLETE        1    /* MACSBUG_ON_WRITE_COMPLETE */ 
  87. #define VIRTUAL_MEMORY_CHECK            0    /* VIRTUAL_MEMORY_CHECK requires LOCK_MEMORY */
  88.  
  89. #if LOG
  90. #define LOGGING(x)    x
  91. #include <stdio.h>
  92. #else
  93. #define LOGGING(x)
  94. #endif
  95.  
  96. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  97.     globals
  98.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  99. static struct usbPrinterPBStruct    printerClassRecord;
  100. static FSSpec                            printerClassDriverFileSpec;
  101. LOGGING( static FILE                    *logfile );
  102.  
  103. SInt16    openRef = 0;        // used to only suspend on last close
  104.  
  105. volatile enum{
  106.     kUSBPrintSuspended,
  107.     kUSBPrintResumed
  108.     }wantToBe = kUSBPrintResumed, currentlyAre = kUSBPrintResumed;
  109.  
  110. // These for resuming reads, writes and control calls which were delayed due to resume
  111.  
  112. IOParamPtr Wpb; DCtlPtr Wctl; struct usbPrinterPBStruct *WpPrinterPB;
  113. IOParamPtr Rpb; DCtlPtr Rctl; struct usbPrinterPBStruct *RpPrinterPB;
  114. IOParamPtr Cpb; DCtlPtr Cctl; struct usbPrinterPBStruct *CpPrinterPB;
  115.  
  116. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  117.     prototypes
  118.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  119.  
  120. static void    PrinterDeviceCompletionProc(USBPB *pb);
  121. static void SetNullUSBParamBlock( USBDeviceRef dev, USBPB *pb );
  122. static void    SoftReset( USBPB *usbprint, short interfaceNum );
  123. static void    ClearEndpointHalt( USBPB *usbprint);
  124. static void    CapabilityRequest( USBPB *pb, Ptr p, long length, short config, short interfaceNum, short alternateSetting );
  125. static void    CentronicsStatus( USBPB *usbprint, Ptr p, short interfaceNum );
  126. static void CompletionProc(USBPB *pb);
  127. static OSStatus MyUSBExpertStatusLevel(UInt32 level, USBDeviceRef ref, StringPtr status, UInt32 value);
  128.  
  129.  
  130. void            PrinterDeviceInitiateTransaction(USBPB *pb);
  131.  
  132. OSErr            CFMInitialization( CFragInitBlock *initBlock );
  133.  
  134. Boolean        gUSBVersionNeedsBulkFixPresent;
  135. UInt32        gUSBVersion;
  136.  
  137. void        CheckUSBVersion(void);
  138. OSStatus     SecondaryUSBBulkRead(void *pb, void *result);
  139. OSStatus     SecondaryUSBBulkWrite(void *pb, void *result);
  140. OSStatus     SafeUSBBulkRead(USBPB *pb);
  141. OSStatus     SafeUSBBulkWrite(USBPB *pb);
  142.  
  143. void    CheckUSBVersion(void)
  144. {
  145. OSStatus    err;
  146.  
  147.     err = Gestalt('usbv', (long*)&gUSBVersion);
  148.     if (err == noErr)
  149.         gUSBVersionNeedsBulkFixPresent = (gUSBVersion < kUSBv12);
  150. }
  151.  
  152. OSStatus SecondaryUSBBulkRead(void *pb, void *result)
  153. {
  154.     *(OSStatus*)result = USBBulkRead((USBPB*)pb);
  155.     return noErr;
  156. }
  157.  
  158. OSStatus SecondaryUSBBulkWrite(void *pb, void *result)
  159. {
  160.     *(OSStatus*)result = USBBulkWrite((USBPB*)pb);
  161.     return noErr;
  162. }
  163.  
  164. OSStatus SafeUSBBulkRead(USBPB *pb)
  165. {
  166.     OSStatus    result;
  167.  
  168.     pb->usbFlags = 0;    // BT we may have set the address request flag
  169.     if (gUSBVersionNeedsBulkFixPresent)
  170.     {
  171.         // Use CallSecondaryInterruptHandler2 to call USBBulkRead if
  172.         // less than USB v1.2 present
  173.         CallSecondaryInterruptHandler2(SecondaryUSBBulkRead, nil, pb, &result);
  174.     }
  175.     else
  176.         result = USBBulkRead(pb);
  177.         
  178.     return result;
  179. }
  180.  
  181. OSStatus SafeUSBBulkWrite(USBPB *pb)
  182. {
  183.     OSStatus    result;
  184.  
  185.     pb->usbFlags = 0;    // BT we may have set the address request flag
  186.     if (gUSBVersionNeedsBulkFixPresent)
  187.     {
  188.         // Use CallSecondaryInterruptHandler2 to call USBBulkWrite if
  189.         // less than USB v1.2 present
  190.         CallSecondaryInterruptHandler2(SecondaryUSBBulkWrite, nil, pb, &result);
  191.     }
  192.     else
  193.         result = USBBulkWrite(pb);
  194.         
  195.     return result;
  196. }
  197.  
  198.  
  199.  
  200.  
  201. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  202.     Name:        HexString8
  203.  
  204.     Input Parameters:    
  205.         v                unsigned long value
  206.         
  207.     Output Parameters:
  208.         p                8 bytes: hex string representing value
  209.         
  210.     Description:
  211.  
  212.  
  213.  
  214. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  215. static void
  216. HexString8( unsigned long v, unsigned char *p )
  217. {
  218.     short    shift;
  219.     
  220.     for ( shift = 32-4; shift >= 0; shift -= 4 )
  221.     {
  222.         char c = (v >> shift) & 0x0F;
  223.         *p++ = c + (c > 9? ('A'-10): '0');
  224.     }
  225. }
  226.  
  227. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  228.     Name:        hexstr
  229.  
  230.     Input Parameters:    
  231.         count                number of bytes
  232.         p                    pointer to bytes
  233.         
  234.     Output Parameters:
  235.         q                    hex dump of data
  236.         
  237.     Description:
  238.  
  239.  
  240.  
  241. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  242. void hexstr( long count, char *p, char *q )
  243. {
  244.     char *s = p;
  245.     long i = count;
  246.     for ( ; count > 0; --count, ++p )
  247.     {
  248.         UInt8 hi, lo;
  249.         hi = (*p >> 4)& 0x0F;
  250.         lo = *p & 0x0F;
  251.         *q++ = '0';
  252.         *q++ = 'x';
  253.         *q++ = hi + (hi > 9? 'A' - 10: '0');
  254.         *q++ = lo + (lo > 9? 'A' - 10: '0');
  255.         *q++ = ' ';
  256.     }
  257.     for ( ; i > 0; --i, ++s )
  258.         *q++ = *s < ' ' || *s > 0x7E? '.': *s;
  259. }
  260.  
  261. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  262.     Name:        ForceUpperStr
  263.  
  264.     Input Parameters:    
  265.         s                    pointer to a null terminated string
  266.         
  267.     Output Parameters:
  268.         s                    string modified by using toupper() on each character.
  269.         
  270.     Description:
  271.  
  272.  
  273.  
  274.  
  275. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  276. void 
  277. ForceUpperStr(char *s)
  278. {
  279.     while(*s){
  280.         *s = toupper(*s);
  281.         s++;
  282.     }
  283. }
  284.     
  285. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  286.     Name:        MakeNameRegistrySafeStr
  287.  
  288.     Input Parameters:    
  289.         s                    pointer to a null terminated string
  290.         
  291.     Output Parameters:
  292.         s                    string modified by replacing / with - on each character.
  293.         
  294.     Description:
  295.  
  296.  
  297.  
  298. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  299. void 
  300. MakeNameRegistrySafeStr(char *s)
  301. {
  302.     while (*s)
  303.     {
  304.         if (*s == '/') 
  305.             *s = '-';
  306.         s++;
  307.     }
  308. }
  309.  
  310.  
  311.  
  312. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  313.     Name:        USBStatusStr
  314.  
  315.     Input Parameters:    
  316.         usbStatus            usb error code
  317.         kind                    kPString or kCString
  318.         
  319.     Output Parameters:
  320.         unsigned char *    description of error (c-string or p-string)
  321.  
  322.     Description:
  323.         a simple mapping of errors to human-readable form
  324.  
  325.  
  326.  
  327.  
  328.  
  329. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  330. static unsigned char *
  331. USBStatusStr( OSStatus usbStatus, short kind )
  332. {
  333.     unsigned char *p;
  334.  
  335.     switch ( usbStatus )
  336.     {
  337.         case    kUSBInternalErr:                    p = kPStrPrinterDriverName"Internal error"; break;
  338.         case    kUSBUnknownDeviceErr:                p = kPStrPrinterDriverName"Unknown device"; break;
  339.         case    kUSBUnknownPipeErr:                 p = kPStrPrinterDriverName"Unknown pipe"; break;
  340.         case    kUSBTooManyPipesErr:                p = kPStrPrinterDriverName"Too many pipes"; break;
  341.         case    kUSBIncorrectTypeErr:                p = kPStrPrinterDriverName"Incorrect type"; break;
  342.         case    kUSBRqErr:                            p = kPStrPrinterDriverName"Request error"; break;
  343.         case    kUSBUnknownRequestErr:                p = kPStrPrinterDriverName"Unknown request"; break;
  344.         case    kUSBTooManyTransactionsErr:            p = kPStrPrinterDriverName"Too many transactions"; break;
  345.         case    kUSBAlreadyOpenErr:                    p = kPStrPrinterDriverName"Already open"; break;
  346.         case    kUSBNoDeviceErr:                    p = kPStrPrinterDriverName"No device"; break;
  347.         case    kUSBDeviceErr:                        p = kPStrPrinterDriverName"Device error"; break;
  348.         case    kUSBOutOfMemoryErr:                    p = kPStrPrinterDriverName"Out of memory"; break;
  349.         case    kUSBNotFound:                        p = kPStrPrinterDriverName"Not found"; break;
  350.         case    kUSBPBVersionError:                    p = kPStrPrinterDriverName"Wrong pbVersion"; break;
  351.         case    kUSBPBLengthError:                    p = kPStrPrinterDriverName"pbLength too small"; break;
  352.         case    kUSBCompletionError:                p = kPStrPrinterDriverName"Missing completion routine"; break;
  353.         case    kUSBFlagsError:                        p = kPStrPrinterDriverName"Unused flags not zeroed"; break;
  354.         case    kUSBAbortedError:                    p = kPStrPrinterDriverName"Pipe aborted"; break;
  355.         case    kUSBNoBandwidthError:                p = kPStrPrinterDriverName"No bandwidth available"; break;
  356.         case    kUSBPipeIdleError:                    p = kPStrPrinterDriverName"Pipe is idle"; break;
  357.         case    kUSBPipeStalledError:                p = kPStrPrinterDriverName"Pipe is stalled"; break;
  358.         case    kUSBUnknownInterfaceErr:            p = kPStrPrinterDriverName"Unknown interfaceRef"; break;
  359.         case    kUSBDeviceBusy:                        p = kPStrPrinterDriverName"Device is busy"; break;
  360.         case    kUSBDevicePowerProblem:                p = kPStrPrinterDriverName"Device power problem"; break;
  361.         case    kUSBInvalidBuffer:                    p = kPStrPrinterDriverName"Bad buffer (nil?)"; break;
  362.         case    kUSBDeviceSuspended:                p = kPStrPrinterDriverName"Device is suspended"; break;
  363.         case    kUSBDeviceNotSuspended:                p = kPStrPrinterDriverName"Device is not suspended"; break;
  364.         case    kUSBDeviceDisconnected:                p = kPStrPrinterDriverName"Disconnected during suspend/reset"; break;
  365.         case    kUSBTimedOut:                        p = kPStrPrinterDriverName"Transaction timed out"; break;
  366.  
  367.         case    kUSBLinkErr:                        p = kPStrPrinterDriverName"Link Err"; break;
  368.         case    kUSBCRCErr:                            p = kPStrPrinterDriverName"Comms/Device err, bad CRC";  break;        
  369.         case    kUSBBitstufErr:                        p = kPStrPrinterDriverName"Comms/Device err, bitstuffing"; break;        
  370.         case    kUSBDataToggleErr:                    p = kPStrPrinterDriverName"Comms/Device err, Bad data toggle"; break;        
  371.         case    kUSBEndpointStallErr:                p = kPStrPrinterDriverName"Device didn't understand"; break;        
  372.         case    kUSBNotRespondingErr:                p = kPStrPrinterDriverName"No device, device hung"; break;        
  373.         case    kUSBPIDCheckErr:                    p = kPStrPrinterDriverName"Comms/Device err, PID CRC error"; break;        
  374.         case    kUSBWrongPIDErr:                    p = kPStrPrinterDriverName"Comms/Device err, Bad or wrong PID"; break;        
  375.         case    kUSBOverRunErr:                        p = kPStrPrinterDriverName"Packet too large or more data than buffer"; break;        
  376.         case    kUSBUnderRunErr:                    p = kPStrPrinterDriverName"Less data than buffer"; break;        
  377.         case    kUSBRes1Err:                        p = kPStrPrinterDriverName"kUSBRes1Err"; break;        
  378.         case    kUSBRes2Err:                        p = kPStrPrinterDriverName"kUSBRes1Err"; break;        
  379.         case    kUSBBufOvrRunErr:                    p = kPStrPrinterDriverName"Buffer over run error"; break;        
  380.         case    kUSBBufUnderRunErr:                    p = kPStrPrinterDriverName"Buffer under run error"; break;        
  381.         case    kUSBNotSent1Err:                    p = kPStrPrinterDriverName"Transaction not sent1"; break;        
  382.         case    kUSBNotSent2Err:                    p = kPStrPrinterDriverName"Transaction not sent2"; break;    
  383.         default:
  384.             p = kPStrPrinterDriverName"Unknown error nnnnnnnn";
  385.             HexString8( usbStatus, p + *p - 8 + 1 );
  386.             break;
  387.     }
  388.     
  389.     return kind == kPString? p: p + 1;
  390. }
  391.  
  392. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  393.     Name:        StateStr
  394.  
  395.     Input Parameters:    
  396.         usbRefCon            usb error code
  397.         kind                    kPString or kCString
  398.         
  399.     Output Parameters:
  400.         unsigned char *    description of state (c-string or p-string)
  401.  
  402.     Description:
  403.         a simple mapping of states to human-readable form
  404.  
  405.  
  406.  
  407.  
  408.  
  409. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  410. static unsigned char *
  411. StateStr( OSStatus refCon, short kind )
  412. {
  413.     unsigned char *p;
  414.  
  415.     refCon &= ~(kTransactionPending | kRetryTransaction | kReturnFromDriver);
  416.     switch ( refCon )
  417.     {
  418.         case kUndefined:                            p = kPStrPrinterDriverName"kUndefined"; break;
  419.         case kNilCompletion:                        p = kPStrPrinterDriverName"kNilCompletion"; break;
  420.  
  421.         case kFindInterface_bidirectional:            p = kPStrPrinterDriverName"kFindInterface_bidirectional"; break;
  422.         case kFindInterface_unidirectional:            p = kPStrPrinterDriverName"kFindInterface_unidirectional"; break;
  423.         case kOpenDevice:                            p = kPStrPrinterDriverName"kOpenDevice"; break;
  424.         case kNewInterfaceRef:                        p = kPStrPrinterDriverName"kNewInterfaceRef"; break;
  425.  
  426.         case kSetInterface:                            p = kPStrPrinterDriverName"kSetInterface"; break;
  427.         case kConfigureInterface:                    p = kPStrPrinterDriverName"kConfigureInterface"; break;
  428.         case kGetCapabilityString:                    p = kPStrPrinterDriverName"kGetCapabilityString"; break;
  429.         case kDelayGetCapability:                    p = kPStrPrinterDriverName"kDelayGetCapability"; break;
  430.  
  431.         case kAllocateCapabilityMem:                p = kPStrPrinterDriverName"kAllocateCapabilityMem"; break;
  432.         case kGetFullCapabilityString:                p = kPStrPrinterDriverName"kGetFullCapabilityString"; break;
  433.         case kGetInterface:                            p = kPStrPrinterDriverName"kGetInterface"; break;
  434.         case kFindBulkOutPipe:                        p = kPStrPrinterDriverName"kFindBulkOutPipe"; break;
  435.  
  436.         case kFindBulkInPipe:                        p = kPStrPrinterDriverName"kFindBulkInPipe"; break;
  437.         case kTaskTimeRequired:                        p = kPStrPrinterDriverName"kTaskTimeRequired"; break;
  438.  
  439.         case kGetCentronicsStatus:                    p = kPStrPrinterDriverName"kGetCentronicsStatus"; break;
  440.         case kDelayGetCentronicsStatus:                p = kPStrPrinterDriverName"kDelayGetCentronicsStatus"; break;
  441.  
  442.         case kDeallocateCapbilityString:            p = kPStrPrinterDriverName"kDeallocateCapbilityString"; break;
  443.         default:
  444.             p = kPStrPrinterDriverName"Unknown state nnnnnnnn";
  445.             HexString8( refCon, p + *p - 8 + 1 );
  446.             break;
  447.     }
  448.     return kind == kPString? p: p + 1;    
  449. }
  450.  
  451. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  452.     Name:        HiHex
  453.  
  454.     Input Parameters:    
  455.         v                        only low byte used
  456.         
  457.     Output Parameters:
  458.         <function result>    high nibble represented as ASCII char
  459.         
  460.     Description:
  461.  
  462.  
  463.  
  464. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  465. static unsigned char
  466. HiHex( unsigned char v )
  467. {
  468.     unsigned char    hinibble = (v >> 4) & 0x0f;
  469.     return hinibble + ((hinibble > 9)? ('A'-10): '0');
  470. }
  471.  
  472. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  473.     Name:        LoHex
  474.  
  475.     Input Parameters:    
  476.         v                        only low byte used
  477.         
  478.     Output Parameters:
  479.         <function result>    low nibble represented as ASCII char
  480.         
  481.     Description:
  482.  
  483.  
  484.  
  485. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  486. static unsigned char
  487. LoHex( unsigned char v )
  488. {
  489.     unsigned char    lonibble = v & 0x0f;
  490.     return lonibble + ((lonibble > 9)? ('A'-10): '0');
  491. }
  492.  
  493. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  494.     Name:        immediateError
  495.  
  496.     Input Parameters:    
  497.         
  498.     Output Parameters:
  499.         
  500.     Description:
  501.  
  502.  
  503.  
  504. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  505. static Boolean
  506. immediateError(OSStatus err)
  507. {
  508.     return((err != kUSBPending) && (err != noErr) );
  509. }
  510.  
  511. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  512.     Name:        SetNullUSBParamBlock
  513.  
  514.     Input Parameters:    
  515.         pb                    pointer to USB parameter block
  516.         dev                USB device reference
  517.     Output Parameters:
  518.         pb                    all fields set to default values
  519.  
  520.     Description:
  521.         setup a USB parameter block for use by the current device
  522.  
  523.  
  524.  
  525.  
  526. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  527. static void
  528. SetNullUSBParamBlock( USBDeviceRef dev, USBPB *pb )
  529. {
  530.     pb->qlink = NULL;
  531.     pb->qType = 0;
  532.     pb->pbLength = sizeof(USBPB);
  533.     pb->pbVersion = kUSBCurrentPBVersion;
  534.     pb->usbFlags = 0;
  535.     pb->usbStatus = noErr;
  536.     pb->usbCompletion = (USBCompletion) NULL;
  537.  
  538.     pb->usbReference = dev;
  539. }
  540.  
  541. // BT - 15Jun99, Callback for the suspend call.
  542. static void usbPrintResume(USBPB *pb)
  543. {
  544. IOParamPtr resumePB;
  545. DCtlPtr resumeCtl;
  546. struct usbPrinterPBStruct *resumePrinterPB;
  547.  
  548.     if(pb->usbStatus != noErr)
  549.     {
  550.         MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver USBPrintDoSuspendResume error", pb->usbStatus);
  551.     }
  552.     else
  553.     {
  554.         currentlyAre = kUSBPrintResumed;
  555.         if(Wpb != nil)
  556.         {
  557.             // We have to restart a waiting write
  558.             MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver resumeing write", 0);
  559.             resumeCtl = Wctl;
  560.             resumePrinterPB = WpPrinterPB;
  561.             resumePB = Wpb;
  562.             Wpb = nil;
  563.             QueueWrite(resumePB, resumeCtl, resumePrinterPB);
  564.         }
  565.     
  566.         if(Rpb != nil)
  567.         {
  568.             // We have to restart a waiting write
  569.             MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver resumeing read", 0);
  570.             resumeCtl = Rctl;
  571.             resumePrinterPB = RpPrinterPB;
  572.             resumePB = Rpb;
  573.             Rpb = nil;
  574.             QueueRead(resumePB, resumeCtl, resumePrinterPB);
  575.         }
  576.         if(Cpb != nil)
  577.         {
  578.             // We have to restart a waiting ControlRequest
  579.             MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver resumeing read", 0);
  580.             resumeCtl = Cctl;
  581.             resumePrinterPB = CpPrinterPB;
  582.             resumePB = Cpb;
  583.             Cpb = nil;
  584.             ControlStatusRequests(resumePB, resumeCtl, resumePrinterPB);
  585.         }
  586.     }
  587.     pb->usbRefcon = 0;
  588. }
  589.  
  590. // BT - 15Jun99, work out if we need to and can suspend or resume and do it.
  591. static USBPrintDoSuspendResume(USBDeviceRef ref)
  592. {
  593. static USBPB pb;
  594. OSStatus err = noErr;
  595.     if(wantToBe != currentlyAre)
  596.     {
  597.         if(currentlyAre == kUSBPrintSuspended)
  598.         {
  599.             MyUSBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver resuming device", ref);
  600.             err = USBResumeDeviceByReference(ref);
  601.         }
  602.         else if(wantToBe == kUSBPrintSuspended)
  603.         {
  604.             if( (printerClassRecord.pb.usbCompletion != nil) || 
  605.                 (printerClassRecord.in.usbCompletion != nil) || 
  606.                 (printerClassRecord.out.usbCompletion != nil) )
  607.             {
  608.                 MyUSBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver can't suspend, busy", (UInt32) printerClassRecord.pb.usbCompletion);
  609.                 return(noErr);
  610.             }
  611.         
  612.             if(pb.usbRefcon != 0)
  613.             {
  614.                 MyUSBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver suspend already in process", err);
  615.                 return(noErr);
  616.             }
  617.             MyUSBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver suspending device", ref);
  618.             SetNullUSBParamBlock(ref, &pb);
  619.             pb.usbCompletion = usbPrintResume;
  620.             pb.usbRefcon = 1;
  621.             currentlyAre = kUSBPrintSuspended;
  622.             err = USBSuspendDevice(&pb);
  623.         }
  624.         if( (err != kUSBPending) && (err != noErr) )
  625.         {
  626.             MyUSBExpertStatusLevel(2, ref, "\pUSB print driver USBPrintDoSuspendResume error", err);
  627.         }
  628.     }
  629.     return(noErr);
  630. }
  631.  
  632.  
  633.  
  634.  
  635.  
  636. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  637.     Name:        ParseCapability
  638.  
  639.     Input Parameters:    
  640.         capability            pointer to 1284-1994 capability string
  641.         attribute            pointer to c-string key we're retrieving (terminate with colon)
  642.         *result_length        maximum length of the result 
  643.         
  644.     Output Parameters:
  645.         result                c-string which followed the key and was terminated by semi-colon
  646.                                 (semi-colon has been stripped)
  647.         *result_length        actual length of the result (may be zero)
  648.     
  649.     Description:
  650.         Search for "attribute" in the 1284 "capability" string
  651.         The identifier is terminated with a semi-colon
  652.  
  653.         Return the attribute in result
  654.             null-string if attribute not found.
  655.  
  656.  
  657.  
  658.  
  659.  
  660. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  661. static void
  662. ParseCapability(
  663.     unsigned char    *capability,
  664.     unsigned char    *attribute,
  665.     unsigned char    *result,
  666.     short            *result_length 
  667. )
  668. {
  669.     //
  670.     //    search for "attribute" in the 1284 "capability" string
  671.     //
  672.     //    the identifier is terminated with a semi-colon
  673.     //
  674.     //    return the attribute in result
  675.     //            null-string if attribute not found
  676.     //
  677.     //    <to do> skip blanks, isolate colon, skip blanks
  678.     //
  679.     UInt32                source_length;
  680.     UInt16                target_length;
  681.     unsigned char        *source,
  682.                         *target,
  683.                         *destination;
  684.     Boolean                foundAttribute = false;
  685.     
  686.     //
  687.     //    begin a brute force search
  688.     //
  689.     source = attribute;
  690.     source_length = CStrLen((char *)attribute );
  691.  
  692.     target = capability + 2;    // skip the length
  693.     target_length =  *(UInt16*)capability;
  694.     if (target_length >= 2)
  695.         target_length -= 2;            // don't count the length
  696.     else
  697.         target_length = 0;
  698.         
  699.     while ( target_length >= source_length )
  700.     {
  701.         if ( memcmp( source, target, source_length ) == 0 ){
  702.             foundAttribute = true;
  703.             break;
  704.         }
  705.         --target_length;
  706.         ++target;
  707.     }
  708.     
  709.     *result = '\0';    // empty result
  710.  
  711.     if (foundAttribute)  // we found the attribute string we are looking for, let's copy the result
  712.     {
  713.         destination = result;
  714.     
  715.         target += source_length;
  716.         target_length -= source_length;    // skip the attribute string
  717.     
  718.         if ( target_length > 0 )
  719.         {
  720.             //
  721.             //    we found the attribute in the capability string
  722.             //
  723.             while ( destination - result < *result_length )    // arbitrarily limit reply
  724.             {
  725.                 if ( *target == ';' || target_length == 0)
  726.                     break;
  727.                 *destination++ = *target++;        // copy a byte of attribute over
  728.                 --target_length;
  729.             }
  730.             *destination++ = '\0';                        // trailing NUL
  731.             *result_length = destination - result;    // report the length of the data (with trailing NUL)
  732.         }
  733.     }
  734. }
  735.  
  736.  
  737. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  738.     Name:        GetClass
  739.  
  740.     Input Parameters:    
  741.         capability            pointer to 1284-1994 capability string
  742.         *result_length        maximum length of the result 
  743.         
  744.     Output Parameters:
  745.         result                c-string extracted from the MODEL key
  746.         *result_length        actual length of the result  (may be zero)
  747.         
  748.     Description:
  749.         CLASS is a Microsoft extension to the 1284-capability string
  750.         if we don't find it
  751.             we assume that the device is a printer
  752.         Since the USB hardware has already indicated this, we're really allowing
  753.         devices which aren't printers to be reached via the DRVRs we've installed.
  754.  
  755.  
  756.  
  757.  
  758. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  759. static void
  760. GetClass(
  761.     unsigned char    *capability,
  762.     unsigned char    *result,
  763.     short            *result_length
  764. )
  765. {
  766.     //
  767.     //    We supply the upper-case PRINTER to be consistent with 1284-1994
  768.     //        if we don't find a class.
  769.     //
  770.     ParseCapability( capability, (unsigned char *) "CLASS:", result, result_length);
  771.     if ( *result == '\0' )
  772.         ParseCapability( capability, (unsigned char *) "CLS:", result, result_length);
  773.     if ( *result == '\0' )
  774.         CStrCopy( (char *)result, "PRINTER" );
  775. }
  776.  
  777.  
  778. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  779.     Name:        GetModel
  780.  
  781.     Input Parameters:    
  782.         capability            pointer to 1284-1994 capability string
  783.         *result_length        maximum length of the result 
  784.         
  785.     Output Parameters:
  786.         result                c-string extracted from the MODEL key
  787.         *result_length        actual length of the result  (may be zero)
  788.             
  789.     Description:
  790.         MODEL is a required field of the 1284-capability string
  791.         MODEL may be abbreviated MDL
  792.  
  793.  
  794.  
  795.  
  796. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  797. static void
  798. GetModel(
  799.     unsigned char    *capability, 
  800.     unsigned char    *result,
  801.     short            *result_length
  802. )
  803. {
  804.     //
  805.     //    Most manufacturers abbreviate, so we search for MDL first
  806.     //
  807.     ParseCapability( capability, (unsigned char *) "MDL:", result, result_length );
  808.     if ( *result == '\0' )
  809.         ParseCapability( capability, (unsigned char *) "MODEL:", result, result_length );
  810. }
  811.  
  812.  
  813. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  814.     Name:        GetCommandSet
  815.  
  816.     Input Parameters:    
  817.         
  818.     Output Parameters:
  819.         
  820.     Description:
  821.  
  822.  
  823.  
  824.  
  825. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  826. static void
  827. GetCommandSet(
  828.     unsigned char    *capability, 
  829.     unsigned char    *result,
  830.     short              *result_length
  831. )
  832. {
  833.     //
  834.     //    COMMAND-SET is a required field of the 1284-capability string
  835.     //    COMMAND-SET may be abbreviated CMD
  836.     //
  837.     ParseCapability( capability, (unsigned char *) "CMD:", result, result_length );
  838.     if ( *result == '\0' )
  839.         ParseCapability( capability, (unsigned char *) "COMMAND SET:", result, result_length );
  840. }
  841.  
  842. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  843.     Name:        GetManufacturer
  844.  
  845.     Input Parameters:    
  846.         
  847.     Output Parameters:
  848.         
  849.     Description:
  850.  
  851.  
  852.  
  853. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  854. static void
  855. GetManufacturer(
  856.     unsigned char *capability, 
  857.     unsigned char *result,
  858.     short *result_length
  859. )
  860. {
  861.     //
  862.     //    MANUFACTURER is a required field of the 1284-capability string
  863.     //    MANUFACTURER may be abbreviated MFG
  864.     //
  865.     ParseCapability( capability, (unsigned char *) "MFG:", result, result_length );
  866.     if ( *result == '\0' )
  867.         ParseCapability( capability, (unsigned char *) "MANUFACTURER:", result, result_length );
  868.     if ( *result == '\0' )
  869.         ParseCapability( capability, (unsigned char *) "HMFG:", result, result_length );
  870. }
  871.  
  872.  
  873. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  874.     Name:        DeregisterDevice
  875.  
  876.     Input Parameters:    
  877.         pPrinterPB
  878.  
  879.     Output Parameters:
  880.         <none>
  881.         
  882.     Description:
  883.         remove the device from the name registry
  884.  
  885.  
  886.  
  887.  
  888.  
  889. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  890. #define kMinNameLength    27
  891. #define kMinModelLength    25
  892. #define kMinClassLength    23
  893.  
  894. static OSStatus
  895. DeregisterDevice( struct usbPrinterPBStruct *pPrinterPB )
  896. {
  897. RegEntryID            self, child, parent;
  898. RegEntryIter         cookie;
  899.  
  900. OSStatus    err = noErr;
  901. Str255        tempStr1,tempStr2;
  902. UInt32        nameLength, modelLength,devclassLength;
  903. Boolean     done = false;
  904.  
  905.     MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Removing the printer from the name registry", 0 );
  906.     // delete the printer node
  907.     // print out the printer's name (which is the same as the node name)
  908.     nameLength = CStrLen((char *)pPrinterPB->name);
  909.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer name:  "));
  910.     CStrCat((char *)tempStr1, (char *)pPrinterPB->name);
  911.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  912.     MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, nameLength );
  913.     
  914.     // locate the model node (parent of printer), and delete it if the printer has no siblings
  915.     if (nameLength<kMinNameLength)
  916.     {
  917.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer name string is not long enough!", nameLength);
  918.     }
  919.     else
  920.     {
  921.         RegistryEntryIDInit( &self );
  922.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name , &self );
  923.         if ( err == noErr )
  924.         {    
  925.             err = RegistryEntryDelete( &self);
  926.         }
  927.         else
  928.         {
  929.             MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Printer node not found!", err );
  930.         }
  931.         RegistryEntryIDDispose(&self);
  932.         
  933.     }
  934.  
  935.  
  936.     // print out the printer's model (which is the same as the node's parent)
  937.     modelLength = CStrLen((char *)pPrinterPB->model);
  938.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer model: "));
  939.     CStrCat((char *)tempStr1, (char *)pPrinterPB->model);
  940.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  941.     MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, modelLength );
  942.     
  943.  
  944.     // locate the model node (parent of printer), and delete it if the printer has no siblings
  945.     if (modelLength<kMinModelLength)
  946.     {
  947.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer model string is not long enough!", modelLength);
  948.     }
  949.     else
  950.     {
  951.         RegistryEntryIDInit( &parent );
  952.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->model , &parent );
  953.         if ( err == noErr )
  954.         {    
  955.             RegistryEntryIDInit(&child);
  956.             
  957.             err = RegistryEntryIterateCreate(&cookie);
  958.             if (err == noErr)
  959.                 err = RegistryEntryIterateSet(&cookie, &parent);
  960.             if (err == noErr)
  961.                 err = RegistryEntryIterate(&cookie, kRegIterChildren, &child, &done);
  962.             if ((err == noErr) && done)
  963.             {
  964.                 MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"No siblings detected, so delete the parent of printer", 0 );
  965.                 err = RegistryEntryDelete(&parent);
  966.             }
  967.             else
  968.             {
  969.                 MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Siblings (or error) detected.  Leaving parent in place", err );
  970.             }
  971.             RegistryEntryIterateDispose(&cookie);
  972.         }
  973.         else
  974.         {
  975.             MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Parent node not found!", err );
  976.         }
  977.         RegistryEntryIDDispose(&parent);
  978.     }
  979.     
  980.     // print out the printer's model (which is the same as the node's parent)
  981.     devclassLength = CStrLen((char *)pPrinterPB->devclass);
  982.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer class: "));
  983.     CStrCat((char *)tempStr1, (char *)pPrinterPB->devclass);
  984.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  985.     MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, devclassLength );
  986.     
  987.  
  988.     // locate the class node (parent of model), and delete it if the class has no siblings
  989.     if (devclassLength<kMinClassLength)
  990.     {
  991.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer class string not long enough!", devclassLength);
  992.     }
  993.     else
  994.     {
  995.         RegistryEntryIDInit( &parent );
  996.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->devclass , &parent );
  997.         if ( err == noErr )
  998.         {    
  999.             RegistryEntryIDInit(&child);
  1000.             
  1001.             err = RegistryEntryIterateCreate(&cookie);
  1002.             if (err == noErr)
  1003.                 err = RegistryEntryIterateSet(&cookie, &parent);
  1004.             if (err == noErr)
  1005.                 err = RegistryEntryIterate(&cookie, kRegIterChildren, &child, &done);
  1006.             if ((err == noErr) && done)
  1007.             {
  1008.                 MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"No models found, so delete the class node", 0 );
  1009.                 err = RegistryEntryDelete(&parent);
  1010.             }
  1011.             else
  1012.             {
  1013.                 MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Models detected.  Leaving class nodes in place", err );
  1014.             }
  1015.             RegistryEntryIterateDispose(&cookie);
  1016.         }
  1017.         else
  1018.         {
  1019.             MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Parent node not found!", err );
  1020.         }
  1021.         RegistryEntryIDDispose(&parent);
  1022.     }
  1023.     
  1024.     return err;
  1025. }
  1026.  
  1027. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1028.     Name:        RegisterDevice
  1029.  
  1030.     Input Parameters:    
  1031.         pPrinterPB
  1032.  
  1033.     Output Parameters:
  1034.         <none>
  1035.         
  1036.     Description:
  1037.         add the device into the name registry; we can't insert just the node
  1038.         if the parent nodes aren't present.
  1039.  
  1040.         if it isn't present
  1041.             insert the device CLASS into the registry
  1042.         if it isn't present
  1043.             insert the device MODEL into the registry
  1044.         finally insert the device itself into the registry
  1045.             we're careful to rename multiple devices
  1046.  
  1047.  
  1048.  
  1049.  
  1050.  
  1051.  
  1052.  
  1053.  
  1054.  
  1055. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1056. static OSStatus
  1057. RegisterDevice( struct usbPrinterPBStruct *pPrinterPB )
  1058. {
  1059.     //
  1060.     //    add the device into the name registry
  1061.     //    if it isn't present
  1062.     //        insert the device CLASS into the registry
  1063.     //    if it isn't present
  1064.     //        insert the device MODEL into the registry
  1065.     //    finally insert the device itself into the registry
  1066.     //        we're careful to rename multiple devices
  1067.     //
  1068. Str255        identification,
  1069.                 devclass,
  1070.                 model,
  1071.                 nameregmodel,
  1072.                 commands,
  1073.                 tempstr;
  1074.                 
  1075. RegEntryID    parent, where, self;
  1076.  
  1077. OSStatus        err;
  1078.  
  1079. short            model_length,
  1080.                 command_length,
  1081.                 class_length;
  1082.  
  1083.  
  1084.     MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Adding the printer to the name registry", 0 );
  1085.     CStrCopy((char *)pPrinterPB->devclass, "");
  1086.     CStrCopy((char *)pPrinterPB->model, "");
  1087.     CStrCopy((char *)pPrinterPB->name, "");
  1088.  
  1089.     command_length = sizeof(commands);
  1090.     GetCommandSet(pPrinterPB->pCapabilityString, commands, &command_length );
  1091.  
  1092.  
  1093.     // get device class and add it to the name registry.  Typically PRINTER or Printer
  1094.     class_length = sizeof(devclass);
  1095.     GetClass( pPrinterPB->pCapabilityString, devclass, &class_length );
  1096.     // force the device class to all uppercase.
  1097.     ForceUpperStr((char *)devclass);
  1098.     
  1099.     CStrCopy( (char *)pPrinterPB->devclass, (char *)"Devices:device-tree:" );
  1100.     CStrCat( (char *)pPrinterPB->devclass, (char *)devclass );
  1101.     
  1102.     RegistryEntryIDInit( &where );
  1103.     err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->devclass, &where );
  1104.     if ( err == nrPathNotFound ) 
  1105.     {
  1106.         //    class not in registry
  1107.         //        create a node for all devices of this CLASS
  1108.         //
  1109.         RegistryEntryIDInit( &parent );
  1110.         err = RegistryCStrEntryLookup( nil, "Devices:device-tree:" , &parent );
  1111.         if ( err == noErr )
  1112.             err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->devclass, &where );
  1113.         RegistryEntryIDDispose(&parent);
  1114.  
  1115.     }
  1116.     
  1117.     CStrToPStr(tempstr, (char *)pPrinterPB->devclass);
  1118.     MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, 0 );
  1119.     
  1120.     //
  1121.     //    add this model into the name registry of this class
  1122.     //
  1123.     if ( err == noErr )
  1124.     {
  1125.         model_length = sizeof(model);
  1126.         GetModel( pPrinterPB->pCapabilityString, model, &model_length );
  1127.         CStrCopy( (char *)nameregmodel, (char *)model);
  1128.         MakeNameRegistrySafeStr((char *)nameregmodel);
  1129.         if ( *model != '\0' )
  1130.         {
  1131.             CStrCopy( (char *)pPrinterPB->model, "Devices:device-tree:" );
  1132.             CStrCat( (char *)pPrinterPB->model, (char *)devclass );
  1133.             CStrCat( (char *)pPrinterPB->model, ":" );
  1134.             if ( *model == '\0'  )
  1135.             {
  1136.                 CStrCat( (char *)pPrinterPB->model, (char *)"USB_PRINTERCLASS" );
  1137.             }
  1138.             else
  1139.             {
  1140.                 CStrCat( (char *)pPrinterPB->model, (char *)nameregmodel );
  1141.             }
  1142.             RegistryEntryIDInit( &self );
  1143.             err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->model , &self );
  1144.             if ( err != noErr )
  1145.             {
  1146.                 // model not in registry
  1147.                 err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->model, &self );
  1148.             }
  1149.             
  1150.             RegistryEntryIDDispose(&self);
  1151.         }
  1152.         CStrToPStr(tempstr, (char *)pPrinterPB->model);
  1153.         MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, 0 );
  1154.     }
  1155.     
  1156.     //
  1157.     //    add this instance of this model of this class
  1158.     //        into the name registry
  1159.     //
  1160.     if ( *model == '\0'  )
  1161.     {
  1162.         //
  1163.         //    possibly the cable isn't firmly connected or the printer isn't switched on
  1164.         //
  1165.         err = kUSBInternalErr;
  1166.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Model undefined", 0);
  1167.     }
  1168.     if ( err == noErr )
  1169.     {
  1170.         //
  1171.         //    start off by identifying the device simply by the model name
  1172.         //        increment the numeric suffix until we successfully registry the device
  1173.         //
  1174.         Str32    suffix;
  1175.         short    numeric_suffix;
  1176.  
  1177.         CStrCopy( (char *)identification, (char *)nameregmodel );
  1178.         RegistryEntryIDInit( &self );
  1179.         for ( numeric_suffix = 1; numeric_suffix < MAX_SUFFIX; ++numeric_suffix )
  1180.         {
  1181.             CStrCopy( (char *)pPrinterPB->name, "Devices:device-tree:" );
  1182.             CStrCat( (char *)pPrinterPB->name, (char *)devclass );
  1183.             CStrCat( (char *)pPrinterPB->name, ":" );
  1184.             CStrCat( (char *)pPrinterPB->name, (char *)nameregmodel );
  1185.             CStrCat( (char *)pPrinterPB->name, ":" );
  1186.             CStrCat( (char *)pPrinterPB->name, (char *)identification );
  1187.             err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name , &self );
  1188.             if ( err != noErr )
  1189.             {
  1190.                 // enter device in registry
  1191.                 err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->name, &self );
  1192.                 if ( err == noErr )
  1193.                 {
  1194.                     CStrCopy( (char *)identification, (char *)model );
  1195.                     if (numeric_suffix > 1)
  1196.                     {
  1197.                         sprintf( (char *)suffix, " %d", numeric_suffix-1 );
  1198.                         CStrCat( (char *)identification, (char *)suffix );
  1199.                     }
  1200.                     err = RegistryPropertyCreate( &self, "modelName", identification, strlen((char *)identification) );
  1201.                 }
  1202.                 if ( err == noErr )
  1203.                     err = RegistryPropertyCreate( &self, "drvrOut", &pPrinterPB->driverOutName, 1 + pPrinterPB->driverOutName[0] );
  1204.                 if ( err == noErr )
  1205.                     err = RegistryPropertyCreate( &self, "outRef", &pPrinterPB->outRefNum, sizeof(pPrinterPB->outRefNum) );
  1206.                 
  1207.                 if (pPrinterPB->printerProtocol != kUSBPrinterUnidirectionalProtocol)
  1208.                 {
  1209.                     if ( err == noErr )
  1210.                         err = RegistryPropertyCreate( &self, "drvrIn", &pPrinterPB->driverInName, 1 + pPrinterPB->driverInName[0] );
  1211.                     if ( err == noErr )
  1212.                         err = RegistryPropertyCreate( &self, "inRef", &pPrinterPB->inRefNum, sizeof(pPrinterPB->inRefNum) );
  1213.                 }
  1214.                 if ( err == noErr )
  1215.                     err = RegistryPropertyCreate( &self, "privateData", &pPrinterPB, sizeof(pPrinterPB) );
  1216.                 if ( err == noErr )
  1217.                     err = RegistryPropertyCreate( &self, "read", &pPrinterPB->r, sizeof(QueueUSBReadUPP) );
  1218.                 if ( err == noErr )
  1219.                     err = RegistryPropertyCreate( &self, "write", &pPrinterPB->w, sizeof(QueueUSBWriteUPP) );
  1220.                 if ( err == noErr && *commands != '\0' )
  1221.                     err = RegistryPropertyCreate( &self, "command-set", &commands, command_length );
  1222.                 break;
  1223.             }
  1224.             //
  1225.             //    if this name didn't succeed
  1226.             //        try the next numeric suffix
  1227.             //
  1228.             sprintf( (char *)suffix, " %d", numeric_suffix );
  1229.             CStrCopy( (char *)identification, (char *)nameregmodel );
  1230.             CStrCat( (char *)identification, (char *)suffix );
  1231.         }
  1232.         RegistryEntryIDDispose(&self);
  1233.     }
  1234.     pPrinterPB->printerRegistered = true;
  1235.     
  1236.     CStrToPStr((unsigned char *)tempstr, (char const *)pPrinterPB->name );
  1237.     
  1238.     MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Added printer to name registry", 0 );
  1239.     MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, err );
  1240.     RegistryEntryIDDispose(&where);
  1241.  
  1242.     LOGGING( logfile = fopen( "USBPrinter.log", "wb+" ) );
  1243.     return err;
  1244. }
  1245.  
  1246. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1247.     Name:        LoadResources
  1248.  
  1249.     Input Parameters:
  1250.         pPrinterPB            pointer to class driver's private storage
  1251.         
  1252.     Output Parameters:
  1253.         OSStatus                resource load error
  1254.         
  1255.     Description:
  1256.         Initialize time is the only safe time to to load resources from our file.
  1257.         Here's where we load resources and detach them from the resource manager.
  1258.         Later we'll use these private copies instead of GetResource calls.
  1259.         
  1260.         Using the file spec that we got from the CFMInitialization routine, open
  1261.         our resource fork.
  1262.  
  1263.  
  1264.  
  1265.  
  1266. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1267. static OSStatus
  1268. LoadResources( struct usbPrinterPBStruct *pPrinterPB )
  1269. {
  1270.     short            rf = -1;                // class driver resource fork
  1271.     OSStatus        err;
  1272.  
  1273.     //
  1274.     //    open the resource fork of this class driver
  1275.     //
  1276.     rf = FSpOpenResFile( &printerClassDriverFileSpec,fsRdPerm );
  1277.     err = ResError();
  1278.     
  1279.     //
  1280.     //    load the DRVR that we'll stick in the unit table
  1281.     //
  1282.     pPrinterPB->hDrvr = NULL;
  1283.     if ( err == noErr )
  1284.     {
  1285.         pPrinterPB->hDrvr = (DRVRHeaderHandle) Get1Resource( 'DRVR',  kUSBParallelDrvrRsrcID );
  1286.         if ( pPrinterPB->hDrvr != NULL )
  1287.             DetachResource( (Handle) pPrinterPB->hDrvr );
  1288.         err = ResError();
  1289.     }
  1290.     
  1291.     if ( rf != -1 )
  1292.         CloseResFile( rf );
  1293.     
  1294.     return err;
  1295. }
  1296.  
  1297. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1298.     Name:        InstallDrivers
  1299.  
  1300.     Input Parameters:
  1301.         pPrinterPB
  1302.         
  1303.     Output Parameters:
  1304.         OSStatus            error code
  1305.         
  1306.     Description:
  1307.         install read and write drivers in the unit table
  1308.             we have separate drivers so that we can support a full-duplex protocol
  1309.         rename the driver we just installed (so multiple copies don't conflict)
  1310.         We use the DRVR -refnum-1 so that the driver name has the same hex chars
  1311.             as the driver number (for manual verification in MacsBug)
  1312.  
  1313.  
  1314.  
  1315.  
  1316.  
  1317.  
  1318. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1319. static OSStatus
  1320. InstallDrivers( struct usbPrinterPBStruct *pPrinterPB )
  1321. {
  1322.     //
  1323.     //    install the driver in the unit table
  1324.     //    rename the driver we just installed (so multiple copies don't conflict)
  1325.     //    
  1326.     short            refNum;                // DRVR refNum
  1327.     OSStatus        err =  paramErr;    // couldn't find driver
  1328.  
  1329.     if ( pPrinterPB->hDrvr != NULL )
  1330.         err = TradInstallDriverFromHandle( pPrinterPB->hDrvr, kMinDrvrUnitNumber, TradHighestUnitNumber() + 1, &pPrinterPB->outRefNum );
  1331.  
  1332.     if ( err == noErr )
  1333.     {
  1334.         UnitNumber        unit;
  1335.         DriverFlags        flags;
  1336.         DRVRHeaderPtr    hdr;
  1337.         unsigned char    *suffix,        // append "In" and "Out"
  1338.                             *infix;        // driver reference number follows the ".USB"
  1339.  
  1340.         TradGetDriverInformation( pPrinterPB->outRefNum, &unit, &flags, pPrinterPB->driverOutName, &hdr );
  1341.         BlockMove( pPrinterPB->driverOutName, pPrinterPB->driverInName, 1 + pPrinterPB->driverOutName[0] );
  1342.         
  1343.         suffix = pPrinterPB->driverOutName + pPrinterPB->driverOutName[0] - 2;
  1344.         infix = pPrinterPB->driverOutName + kDrvrFirstDigit;
  1345.         infix[0] = HiHex( -pPrinterPB->outRefNum -1 );
  1346.         infix[1] = LoHex( -pPrinterPB->outRefNum -1 );
  1347.         suffix[0] = 'O';
  1348.         suffix[1] = 'u';
  1349.         suffix[2] = 't';
  1350.         TradRenameDriver( pPrinterPB->outRefNum, pPrinterPB->driverOutName );
  1351.         //
  1352.         //    set the driver data to point to our parameter block
  1353.         //
  1354.         err = OpenDriver( pPrinterPB->driverOutName, &refNum );
  1355.         if ( err == noErr )
  1356.         {
  1357.             struct usbPrinterPBStruct *param = pPrinterPB;
  1358.             err = Control( refNum, kDrvrPrivateSetStorage, ¶m );
  1359.             CloseDriver( refNum );
  1360.         }
  1361.         err = TradInstallDriverFromHandle( pPrinterPB->hDrvr, kMinDrvrUnitNumber, TradHighestUnitNumber() + 1, &pPrinterPB->inRefNum );
  1362.         if ( err == noErr )
  1363.         {
  1364.             
  1365.             suffix = pPrinterPB->driverInName + pPrinterPB->driverInName[0] - 1;
  1366.             infix = pPrinterPB->driverInName + kDrvrFirstDigit;
  1367.             infix[0] = HiHex( -pPrinterPB->inRefNum -1 );
  1368.             infix[1] = LoHex( -pPrinterPB->inRefNum -1 );
  1369.             suffix[0] = 'I';
  1370.             suffix[1] = 'n';
  1371.             TradRenameDriver( pPrinterPB->inRefNum, pPrinterPB->driverInName );
  1372.             //
  1373.             //    set the driver data to point to our parameter block
  1374.             //
  1375.             err = OpenDriver( pPrinterPB->driverInName, &refNum );
  1376.             if ( err == noErr )
  1377.             {
  1378.                 struct usbPrinterPBStruct *param = pPrinterPB;
  1379.                 err = Control( refNum, kDrvrPrivateSetStorage, ¶m );
  1380.                 CloseDriver( refNum );
  1381.             }
  1382.         }
  1383.     }
  1384.     
  1385.     return err;
  1386. }
  1387.  
  1388. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1389.     Name:        GetCapability
  1390.  
  1391.     Input Parameters:    
  1392.         
  1393.     Output Parameters:
  1394.         
  1395.     Description:
  1396.         Asynchronous completion.
  1397.  
  1398.  
  1399.  
  1400. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1401. static void
  1402. GetCapability( struct usbPrinterPBStruct *pPrinterPB, unsigned char *p, short length )
  1403. {
  1404.     //
  1405.     //    queue a transaction to retrieve the 1284 capability string
  1406.     //        we must have assigned the interface by this point since the capability string
  1407.     //        may vary with the interface
  1408.     //
  1409.     OSStatus        err;
  1410.     USBPB            *pb = &pPrinterPB->pb;
  1411.  
  1412.     SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  1413.     
  1414.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  1415.     pb->usbBuffer = 0;
  1416.     pb->usbActCount = 0;
  1417.     pb->usbReqCount = 0;
  1418.  
  1419.     pb->usb.cntl.BRequest = kUSBPrintClassGetDeviceID;
  1420.     pb->usb.cntl.WValue = 0;            // configuration
  1421.     pb->usb.cntl.WIndex = (pPrinterPB->interfaceNumber<<8) | pPrinterPB->alternateSetting;
  1422.  
  1423.     pb->usbReqCount = length;
  1424.     pb->usbBuffer = p;
  1425.  
  1426.     pb->usbRefcon |= kTransactionPending;
  1427.     pb->usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  1428.     err = USBDeviceRequest(pb);
  1429.     if(immediateError(err))
  1430.     {
  1431.         USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"GetCapability", 0);
  1432.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1433.         pb->usbRefcon |= kReturnFromDriver;
  1434.     }
  1435. }
  1436.  
  1437. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1438.     Name:        IsLucentCable
  1439.  
  1440.     Input Parameters:    
  1441.         dev            USB device descriptor
  1442.         
  1443.     Output Parameters:
  1444.         Return 1 if the USB device is a USB-parallel cable
  1445.         
  1446.     Description:
  1447.         
  1448.  
  1449.  
  1450.  
  1451. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1452. static short
  1453. IsLucentCable( USBDeviceDescriptor    *dev )
  1454. {
  1455.     return ( USBToHostWord(dev->vendor) == 0x47E && USBToHostWord(dev->product) == 0x1001 )? 1: 0;
  1456. }
  1457.  
  1458.  
  1459. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1460.     Name:        GetInterface
  1461.  
  1462.     Input Parameters:    
  1463.         
  1464.     Output Parameters:
  1465.         
  1466.     Description:
  1467.         Asynchronous completion.
  1468.  
  1469.  
  1470.  
  1471. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1472. static void
  1473. GetInterface( USBPB *pb, UInt8 *alt )
  1474. {
  1475.     //
  1476.     //    make sure we account for any alternate interface currently in use by the device
  1477.     //
  1478.     OSStatus    err;
  1479.  
  1480.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBStandard, kUSBInterface);
  1481.  
  1482.     pb->usb.cntl.BRequest = kUSBRqGetInterface;
  1483.     pb->usb.cntl.WValue = 0; 
  1484.     pb->usb.cntl.WIndex = 0;
  1485.  
  1486.     pb->usbReqCount = sizeof(UInt8);        // single byte is requested
  1487.     pb->usbBuffer = alt;
  1488.  
  1489.     pb->usbStatus = 0;
  1490.     pb->usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  1491.     pb->usbRefcon |= kTransactionPending;
  1492.  
  1493.     err = USBDeviceRequest(pb);
  1494.     if(immediateError(err))
  1495.     {
  1496.         USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"GetInterface", 0);
  1497.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1498.         pb->usbRefcon |= kReturnFromDriver;
  1499.     }
  1500. }
  1501.  
  1502.  
  1503. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1504.     Name:        ReadCompletion
  1505.  
  1506.     Input Parameters:    
  1507.         pb                        USB parameter block
  1508.         
  1509.     Output Parameters:
  1510.         <none>
  1511.  
  1512.     Description:
  1513.         USB read requests complete here.
  1514.         We dequeue the MacOS DRVR read requests
  1515.  
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522.  
  1523. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1524. static void
  1525. ReadCompletion(USBPB *pb)
  1526. {
  1527.     //    call the user completion routine
  1528.     struct usbPrinterPBStruct
  1529.             *pPrinterPB =  (struct usbPrinterPBStruct    *) pb->usbRefcon;
  1530.     IOParamPtr     clientParam = pPrinterPB->readDrvr.pb;
  1531.     OSStatus        err = pb->usbStatus;
  1532.     DCtlPtr            ctlLocal;
  1533.  
  1534. #if MACSBUG_ON_READ_COMPLETE
  1535.     Str255    text;
  1536.     sprintf( (char *)text, " PrinterClass Read Complete(%d): %d", pb->usbStatus, pb->usbActCount );
  1537.     text[0] = CStrLen((char *)text); // c2pstr
  1538.     DebugStr( text );
  1539. #endif
  1540.  
  1541. #if DOUBLE_BUFFER
  1542.     //
  1543.     //    copy the user data from our page aligned buffer
  1544.     //
  1545.     MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion - bytes read  " , (UInt32)pb->usbActCount );
  1546.  
  1547.     if ( pb->usbActCount > 0 )
  1548.         BlockCopy( pPrinterPB->pageReadAlignedBuffer, clientParam->ioBuffer + clientParam->ioActCount, pb->usbActCount );
  1549. #endif
  1550.     //    update the amount of data actually transferred
  1551.     clientParam->ioActCount += pb->usbActCount;
  1552.  
  1553.     switch( pb->usbStatus )
  1554.     {
  1555.         //
  1556.         //    only retry low level hardware problems
  1557.         //        note: abort transactions will end up here as well
  1558.         //
  1559.     case kUSBLinkErr:
  1560.     case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  1561.     case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  1562.     case kUSBDataToggleErr:                        /*  Pipe stall, Bad data toggle */
  1563.     case kUSBNotRespondingErr:                    /*  Pipe stall, No device, device hung */
  1564.     case kUSBPIDCheckErr:                        /*  Pipe stall, PID CRC error */
  1565.     case kUSBWrongPIDErr:                        /*  Pipe stall, Bad or wrong PID */
  1566.         if (  --(pPrinterPB->readRetryCount) >= 0 ) // = is there so we don't retry clear endpoints forever
  1567.         {
  1568.             if(pPrinterPB->readStatus == noErr)
  1569.             {
  1570.                 pPrinterPB->readStatus = pb->usbStatus;
  1571.             }
  1572.             // we got an error, and we still want to retry, clear any stalls
  1573.             MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion retry" , pb->usbStatus );
  1574.             USBClearPipeStallByReference(pPrinterPB->readPipeRef);
  1575.             pb->usbStatus = noErr;
  1576.  
  1577.             
  1578.             MyUSBExpertStatusLevel(3, pb->usbReference, kPStrPrinterDriverName"**** ReadCompletion clearing endpoint halt *****" , pb->usbStatus );
  1579.             ClearEndpointHalt(pb);    // Sets up PB
  1580.             USBDeviceRequest(pb);
  1581.             return;
  1582.         }
  1583.         break;
  1584.     case kUSBAbortedError:                        /* user cancel, or hot unplug */
  1585.         MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion abortedError" , pb->usbStatus );
  1586.         USBClearPipeStallByReference(pPrinterPB->readPipeRef);
  1587.         USBClearPipeStallByReference(pPrinterPB->deviceRef);
  1588.         break;
  1589.         //
  1590.         //    any other error will be reported to the client
  1591.         //
  1592.     default:
  1593.     case noErr:
  1594.         break;
  1595.     }
  1596.     
  1597. //    (pPrinterPB->readStatus != noErr)    
  1598. //or 
  1599. //    (pPrinterPB->readStatus == noErr) and (pb->usbActCount == pb->usbReqCount)
  1600.  
  1601. //                  read Status == noErr
  1602. //                     true        false
  1603. //
  1604. //  act=req  t      r         r
  1605. //
  1606. //           f      x         r
  1607.  
  1608.     
  1609.     if ( (pb->usbStatus == noErr) &&                                 // there were no problems
  1610.          (pPrinterPB->readRetryCount > 0) &&                        // there were no enough problems
  1611.          
  1612.         ( (pPrinterPB->readStatus != noErr) ||
  1613.          (pb->usbActCount == pb->usbReqCount)  ) &&                    // we got all the data we requested
  1614. // BT don't do this or we'll never retry read errors. However we need to do this to finish short packets.
  1615. //  
  1616.  
  1617.         (clientParam->ioActCount < clientParam->ioReqCount) )        // we still want more data
  1618.     {
  1619.         //
  1620.         //    haven't finish the client's request
  1621.         //        update the pointers and start another bulk read transaction
  1622.         //
  1623. #if LOCK_MEMORY
  1624.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1625.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion UnlockMem failed" ) );
  1626. #endif
  1627.         pb->usbBuffer = clientParam->ioBuffer + clientParam->ioActCount;
  1628.         pb->usbReqCount = clientParam->ioReqCount - clientParam->ioActCount;
  1629. #if MAX_USB_TRANSFER_SIZE
  1630.         if ( pb->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1631.             pb->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1632. #endif
  1633. #if DOUBLE_BUFFER
  1634.         //
  1635.         //    make sure we have enough room in our buffer
  1636.         //
  1637.         if ( pb->usbReqCount > pPrinterPB->pageReadAlignedBufferSize )
  1638.             pb->usbReqCount = pPrinterPB->pageReadAlignedBufferSize;
  1639.         pb->usbBuffer = pPrinterPB->pageReadAlignedBuffer;
  1640. #endif
  1641.  
  1642.         pPrinterPB->readStatus = noErr;
  1643. #if LOCK_MEMORY
  1644.         err = LockMemory( pb->usbBuffer, pb->usbReqCount );
  1645.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion LockMem failed" ) );
  1646.         if ( err == noErr )
  1647. #endif
  1648.             err = SafeUSBBulkRead( pb );    // Note this is probably hanging off the if above.
  1649.         if ( immediateError(err) )
  1650.         {
  1651.             MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion finish immed err" , err );
  1652.  
  1653.             pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1654.             if ( pPrinterPB->readDrvr.ctl != NULL )
  1655.             {
  1656.                 ctlLocal = pPrinterPB->readDrvr.ctl;
  1657.                 pPrinterPB->readDrvr.ctl = NULL;
  1658.                 CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, err, clientParam, ctlLocal ); 
  1659.             }
  1660.         }
  1661.     }
  1662.     else
  1663.     {
  1664.         if(pPrinterPB->readStatus != noErr)
  1665.         {
  1666.             pb->usbStatus = pPrinterPB->readStatus;
  1667.         }
  1668.         //
  1669.         //        either we have an error which we're not retrying
  1670.         //            or we successfully completed
  1671.         //
  1672. #if LOCK_MEMORY
  1673.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1674.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion concluded UnlockMem failed" ) );
  1675. #endif
  1676.         IF_DEBUG( if (pb->usbStatus != noErr) MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion Error" , pb->usbStatus ) );
  1677.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1678.         MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"readDrvr.ctl = " , (UInt32)pPrinterPB->readDrvr.ctl );
  1679.         if ( pPrinterPB->readDrvr.ctl != NULL )
  1680.         {
  1681.             ctlLocal = pPrinterPB->readDrvr.ctl;
  1682.             pPrinterPB->readDrvr.ctl = NULL;
  1683.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, ctlLocal); 
  1684.         }
  1685.         else
  1686.         {
  1687.             IF_DEBUG( DebugStr( kPStrPrinterDriverName"ReadCompletion() pPrinterPB->readDrvr.ctl == NULL" ) );
  1688.         }
  1689.         MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB PRint, read completion do suspend resume" , pb->usbReference);
  1690.         USBPrintDoSuspendResume(pPrinterPB->interfaceRef);
  1691.     }
  1692. }
  1693.  
  1694.  
  1695. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1696.     Name:        WriteCompletion
  1697.  
  1698.     Input Parameters:    
  1699.         pb                        USB parameter block
  1700.         
  1701.     Output Parameters:
  1702.         <none>
  1703.  
  1704.     Description:
  1705.         USB write requests complete here.
  1706.         We dequeue the MacOS DRVR write requests
  1707.  
  1708.         when breaking up transactions we use ioActCount to determine how much remains 
  1709.                 of the original request and where the next request begins
  1710.         if we've failed with a USB error
  1711.             usbActCount indicates how much data has been transferred with the current request
  1712.             and if the retry count hasn't been exceeded
  1713.                 we proceed as if we'd just requested that much in this transactions
  1714.         note the retry count is cumulative for the original client request
  1715.             not for each usb transaction
  1716.  
  1717.  
  1718.  
  1719.  
  1720.  
  1721.  
  1722.  
  1723.  
  1724.  
  1725.  
  1726. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1727. static void
  1728. WriteCompletion(USBPB *pb)
  1729. {
  1730.     //    call the user completion routine
  1731.     struct usbPrinterPBStruct
  1732.                     *pPrinterPB =  (struct usbPrinterPBStruct    *) pb->usbRefcon;
  1733.     IOParamPtr     clientParam = pPrinterPB->writeDrvr.pb;
  1734.     DCtlPtr            ctlLocal;
  1735.     OSStatus        err = pb->usbStatus;
  1736.  
  1737. #if MACSBUG_ON_WRITE_COMPLETE
  1738.     Str255    text;
  1739.     sprintf( (char *)text, " PrinterClass Write Complete(%d): %d", pb->usbStatus, pb->usbActCount );
  1740.     text[0] = CStrLen((char *)text); // c2pstr
  1741.     DebugStr( text );
  1742. #endif
  1743.  
  1744.     //    update the amount of data actually transferred
  1745.     clientParam->ioActCount += pb->usbActCount;
  1746.     MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion - bytes written  " , (UInt32)pb->usbActCount);
  1747.  
  1748.     switch( pb->usbStatus )
  1749.     {
  1750.         //
  1751.         //    only retry low level hardware problems
  1752.         //        note: abort transactions will end up here as well
  1753.         //
  1754.     case kUSBLinkErr:
  1755.     case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  1756.     case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  1757.     case kUSBDataToggleErr:                        /*  Pipe stall, Bad data toggle */
  1758.     case kUSBNotRespondingErr:                    /*  Pipe stall, No device, device hung */
  1759.     case kUSBPIDCheckErr:                        /*  Pipe stall, PID CRC error */
  1760.     case kUSBWrongPIDErr:                        /*  Pipe stall, Bad or wrong PID */
  1761.         if (  --(pPrinterPB->writeRetryCount) >= 0 ) // = is there so we don't retry clearendpoints forever
  1762.         {
  1763.             if(pPrinterPB->writeStatus == noErr)
  1764.             {
  1765.                 pPrinterPB->writeStatus = pb->usbStatus;
  1766.             }
  1767.             // we got an error, and we still want to retry, clear any stalls
  1768.             MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion retry" , pb->usbStatus );
  1769.             USBClearPipeStallByReference(pPrinterPB->writePipeRef);
  1770.             pb->usbStatus = noErr;
  1771.             
  1772.             MyUSBExpertStatusLevel(3, pb->usbReference, kPStrPrinterDriverName"**** WriteCompletion clearing endpoint halt *****" , pb->usbStatus );
  1773.             ClearEndpointHalt(pb);    // Sets up PB
  1774.             USBDeviceRequest(pb);
  1775.             return;
  1776.             
  1777.         }
  1778.         break;
  1779.     case kUSBAbortedError:                        /* user cancel, or hot unplug */
  1780.         USBClearPipeStallByReference(pPrinterPB->writePipeRef);
  1781.         USBClearPipeStallByReference(pPrinterPB->deviceRef);
  1782.         break;
  1783.         //
  1784.         //    any other error will be reported to the client
  1785.         //
  1786.     default:
  1787.     case noErr:
  1788.         break;
  1789.     }
  1790.  
  1791.     if ( (pPrinterPB->writeRetryCount > 0) && 
  1792.          (pb->usbStatus == noErr) &&
  1793.          (clientParam->ioActCount < clientParam->ioReqCount) )
  1794.     {
  1795.         //
  1796.         //    haven't finish the client's request
  1797.         //        update the pointers and start another bulkOut transaction
  1798.         //
  1799. #if LOCK_MEMORY
  1800.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1801.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion UnlockMem failed" ) );
  1802. #endif
  1803.         pb->usbBuffer = clientParam->ioBuffer + clientParam->ioActCount;
  1804.         pb->usbReqCount = clientParam->ioReqCount - clientParam->ioActCount;
  1805. #if MAX_USB_TRANSFER_SIZE
  1806.         if ( pb->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1807.             pb->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1808. #endif
  1809. #if DOUBLE_BUFFER
  1810.         //
  1811.         //    make sure we have enough room in our buffer
  1812.         //    then copy the user data into our page aligned buffer
  1813.         //
  1814.         if ( pb->usbReqCount > pPrinterPB->pageWriteAlignedBufferSize )
  1815.             pb->usbReqCount = pPrinterPB->pageWriteAlignedBufferSize;
  1816.             
  1817.         BlockCopy( pb->usbBuffer, pPrinterPB->pageWriteAlignedBuffer, pb->usbReqCount );
  1818.         pb->usbBuffer = pPrinterPB->pageWriteAlignedBuffer;
  1819.         
  1820. #endif
  1821.  
  1822.  
  1823.         pPrinterPB->writeStatus = noErr;
  1824. #if LOCK_MEMORY
  1825.         err = LockMemory( pb->usbBuffer, pb->usbReqCount );
  1826.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion LockMem failed" ) );
  1827.         if ( err == noErr )
  1828. #endif
  1829.             err = SafeUSBBulkWrite( pb );    // Note this is probably hanging off the if above.
  1830.         if ( immediateError(err) )
  1831.         {
  1832.             MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion finish immed err" , err );
  1833.  
  1834.             pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1835.             if ( pPrinterPB->writeDrvr.ctl != NULL )
  1836.             {
  1837.                 ctlLocal = pPrinterPB->writeDrvr.ctl;
  1838.                 pPrinterPB->writeDrvr.ctl = NULL;
  1839.                 CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, err, clientParam, ctlLocal ); 
  1840.             }
  1841.         }
  1842.     }
  1843.     else
  1844.     {
  1845.         if(pPrinterPB->writeStatus != noErr)
  1846.         {
  1847.             pb->usbStatus = pPrinterPB->writeStatus;
  1848.         }
  1849.         //
  1850.         //        either we have an error which we're not retrying
  1851.         //            or we successfully completed
  1852.         //
  1853. #if LOCK_MEMORY
  1854.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1855.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion concluded UnlockMem failed" ) );
  1856. #endif
  1857.  
  1858.         IF_DEBUG( if (pb->usbStatus != noErr) MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion Error" , pb->usbStatus ) );
  1859.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1860.  
  1861.  
  1862.         MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"writeDrvr.ctl = " , (UInt32)pPrinterPB->writeDrvr.ctl );
  1863.         if ( pPrinterPB->writeDrvr.ctl != NULL )
  1864.         {
  1865.             ctlLocal = pPrinterPB->writeDrvr.ctl;
  1866.             pPrinterPB->writeDrvr.ctl = NULL;
  1867.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, ctlLocal ); 
  1868.         }
  1869.         else
  1870.         {
  1871.             IF_DEBUG( DebugStr( kPStrPrinterDriverName"WriteCompletion() pPrinterPB->writeDrvr.ctl == NULL" ) );
  1872.         }
  1873.         MyUSBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB PRint, write completion do suspend resume" , pb->usbReference );
  1874.         
  1875.         if (gUSBVersion >= kUSBv135)
  1876.         {
  1877.             USBPrintDoSuspendResume(pPrinterPB->interfaceRef);
  1878.         }
  1879.     }
  1880. }
  1881.  
  1882. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1883.     Name:        QueueRead
  1884.  
  1885.     Input Parameters:    
  1886.         pb                        MacOS device manager parameter block
  1887.         ctl                    device manager dCtl block
  1888.         pPrinterPB            current printing device class's storage
  1889.         
  1890.     Output Parameters:
  1891.         <none>
  1892.  
  1893.     Description:
  1894.         MacOS DRVR read requests are re-queued here to the USB
  1895.         Since we only allow one read request pending at a time, we're able
  1896.         to use the USB refCon to point to our class driver's storage.
  1897.  
  1898.  
  1899.  
  1900.  
  1901. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1902. void
  1903. QueueRead( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  1904. {    
  1905.     OSStatus    err;
  1906.     USBPB        *usbprint = &pPrinterPB->in;
  1907.     
  1908. #if MACSBUG_ON_READ
  1909.     Str255    text;
  1910.  
  1911.     sprintf( (char *)text, " PrinterClass Read: %d @ %08x", pb->ioReqCount, pb->ioBuffer );
  1912.     text[0] = CStrLen((char *)text); // c2pstr
  1913.     MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  1914.     DebugStr( text );
  1915. #endif
  1916.  
  1917.     // BT - 15Jun99, if we're not currently awake, delay this until we are.
  1918.     if(currentlyAre == kUSBPrintSuspended)
  1919.     {
  1920.         pb->ioResult = ioInProgress;
  1921.         MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, delaying read for resume", 0 );
  1922.         RpPrinterPB = pPrinterPB;
  1923.         Rctl = ctl;
  1924.         Rpb = pb;
  1925.         if( (currentlyAre != kUSBPrintSuspended) && (Rpb != nil) )
  1926.         {
  1927.             MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, resumed while we wern't looking", 0 );
  1928.             // resumed and executed this while we were doing this.
  1929.             return;
  1930.         }
  1931.         else
  1932.         {
  1933.             // now wait for resume to happen
  1934.             MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, let resume take over", 0 );
  1935.             return;
  1936.         }        
  1937.     }
  1938.  
  1939.  
  1940.     pb->ioActCount = 0;        // nothing transfered yet
  1941.     if ( pPrinterPB->terminating )
  1942.         pb->ioResult = abortErr;
  1943.     else
  1944.     {
  1945.  
  1946.         pPrinterPB->readRetryCount = 5;
  1947.         pPrinterPB->readStatus = noErr;
  1948.         pPrinterPB->readDrvr.pb= pb;
  1949.         pPrinterPB->readDrvr.ctl = ctl;
  1950.         if (( pPrinterPB->readPipeRef != NULL ) && (pPrinterPB->printerConfigured))
  1951.         {
  1952.             SetNullUSBParamBlock( pPrinterPB->readPipeRef,  usbprint );
  1953.             MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Set up to do bulk read", pb->ioReqCount );
  1954.             usbprint->usbActCount = 0;
  1955.             usbprint->usbBuffer = pb->ioBuffer;
  1956.             usbprint->usbReqCount = pb->ioReqCount;
  1957.  
  1958. #if MAX_USB_TRANSFER_SIZE
  1959.             //
  1960.             //    the completion routine will queue another BulkWrite until we exhaust the data
  1961.             //        or there is an error which can't be retried
  1962.             //
  1963.             if ( usbprint->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1964.                 usbprint->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1965. #endif
  1966. #if DOUBLE_BUFFER
  1967.             //
  1968.             //    make sure we have enough room in our buffer
  1969.             //    then copy the user data into our page aligned buffer
  1970.             //
  1971.             if ( usbprint->usbReqCount > pPrinterPB->pageReadAlignedBufferSize )
  1972.                 usbprint->usbReqCount = pPrinterPB->pageReadAlignedBufferSize;
  1973.             usbprint->usbBuffer = pPrinterPB->pageReadAlignedBuffer;
  1974. #endif
  1975.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  1976.             usbprint->usbCompletion = (USBCompletion) ReadCompletion;
  1977.             
  1978.             pb->ioResult = ioInProgress;
  1979. #if LOCK_MEMORY
  1980.             err = LockMemory( usbprint->usbBuffer, usbprint->usbReqCount );
  1981.             IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"QueueRead LockMem failed" ) );
  1982.             if ( err == noErr )
  1983. #endif
  1984.             err = SafeUSBBulkRead( usbprint );
  1985.             if ( immediateError(err) )
  1986.             {
  1987.                 MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Error doing bulk read",err );
  1988.                 IF_DEBUG( DebugStr( USBStatusStr(err, kPString) ) );
  1989.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1990.                 pb->ioResult = err;
  1991.             }
  1992.         }
  1993.         else
  1994.         {
  1995.             MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Read to unopened pipe" , usbprint->usbStatus ) ;
  1996.             pb->ioResult = abortErr;
  1997.         }
  1998.     }
  1999. }
  2000.  
  2001. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2002.     Name:        QueueWrite
  2003.  
  2004.     Input Parameters:    
  2005.         pb                        MacOS device manager parameter block
  2006.         ctl                    device manager dCtl block
  2007.         pPrinterPB            current printing device class's storage
  2008.         
  2009.     Output Parameters:
  2010.         <none>
  2011.  
  2012.     Description:
  2013.         MacOS DRVR write requests are re-queued here to the USB
  2014.         Since we only allow one read request pending at a time, we're able
  2015.         to use the USB refCon to point to our class driver's storage.
  2016.  
  2017.  
  2018.  
  2019. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2020. void
  2021. QueueWrite( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  2022. {
  2023.     OSStatus    err;
  2024.     USBPB        *usbprint = &pPrinterPB->out;
  2025. #if VIRTUAL_MEMORY_CHECK
  2026.     //
  2027.     //    dump the VM table
  2028.     //
  2029.     Str255                        text;
  2030.     LogicalToPhysicalTable        *vmTable;
  2031.     MemoryBlock                    *physical;
  2032.     unsigned long                vmCount,
  2033.                                 vmEntry,
  2034.                                 vmTblLength;
  2035. #endif
  2036.  
  2037. #if MACSBUG_ON_WRITE
  2038.     Str255    text;
  2039.     sprintf( (char *)text, " "kCStrPrinterDriverName"%d @ %08x", pb->ioReqCount, pb->ioBuffer );
  2040.     text[0] = CStrLen((char *)text); // c2pstr
  2041.     MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2042.     DebugStr( text );
  2043. #endif
  2044.  
  2045.     // BT - 15Jun99, if we're not currently awake, delay this until we are.
  2046.     if(currentlyAre == kUSBPrintSuspended)
  2047.     {
  2048.         pb->ioResult = ioInProgress;
  2049.         MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, delaying write for resume", 0 );
  2050.  
  2051.         WpPrinterPB = pPrinterPB;
  2052.         Wctl = ctl;
  2053.         Wpb = pb;
  2054.         if( (currentlyAre != kUSBPrintSuspended) && (Wpb != nil) )
  2055.         {
  2056.             MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, resumed while we wern't looking", 0 );
  2057.             // resumed and executed this while we were doing this.
  2058.         }
  2059.         else
  2060.         {
  2061.             // now wait for resume to happen
  2062.             MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, let resume take over", 0 );
  2063.             return;
  2064.         }        
  2065.     }
  2066.  
  2067.  
  2068.  
  2069. #if VIRTUAL_MEMORY_CHECK
  2070.     //
  2071.     //    this check current won't compile without runtime error: need to lock memory, but lock has moved
  2072.     //
  2073.     sprintf( (char *)text, " "kCStrPrinterDriverName"Write: %d @ %08x", pb->ioReqCount, pb->ioBuffer );
  2074.     text[0] = CStrLen((char *)text); // c2pstr
  2075.     MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2076.     
  2077.     vmCount = 127;
  2078.     vmTblLength = (vmCount+1)*sizeof(MemoryBlock);
  2079.     vmTable = (LogicalToPhysicalTable *) NewPtrSys( vmTblLength );
  2080.     LockMemory( vmTable, vmTblLength );
  2081.     LockMemory( &vmCount, sizeof(unsigned long) );
  2082.     vmTable->logical.address = pb->ioBuffer;
  2083.     vmTable->logical.count = pb->ioReqCount;
  2084.     err = GetPhysical( vmTable, &vmCount );
  2085.     
  2086.     if ( err == noErr )
  2087.     {
  2088.         for ( vmEntry = 0, physical = &vmTable->physical[0]; vmEntry < vmCount; ++vmEntry , ++physical)
  2089.         {
  2090.             sprintf( (char *)text, " "kCStrPrinterDriverName"Write: VM @%08x (%d)", physical->address, physical->count );
  2091.             text[0] = CStrLen((char *)text); // c2pstr
  2092.             MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2093.         }
  2094.     }
  2095.     UnlockMemory( vmTable, vmTblLength );
  2096.     UnlockMemory( &vmCount, sizeof(unsigned long) );
  2097. #endif
  2098.     pb->ioActCount = 0;        // nothing transfered yet
  2099.  
  2100.  
  2101.     usbprint->usbStatus = noErr;    // forget about abort and things from previous writes
  2102.     if ( pPrinterPB->terminating )
  2103.         pb->ioResult = abortErr;
  2104.     else
  2105.     {
  2106.         pPrinterPB->writeRetryCount = 5;
  2107.         pPrinterPB->writeStatus = noErr;
  2108.         pPrinterPB->writeDrvr.pb = pb;
  2109.         pPrinterPB->writeDrvr.ctl = ctl;
  2110.         if (( pPrinterPB->writePipeRef != NULL ) && (pPrinterPB->printerConfigured))
  2111.         {
  2112.             SetNullUSBParamBlock( pPrinterPB->writePipeRef,  usbprint );
  2113.             MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Set up to do bulk write", pb->ioReqCount );
  2114.             usbprint->usbActCount = 0;
  2115.             usbprint->usbBuffer = pb->ioBuffer;
  2116.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  2117.             usbprint->usbCompletion = (USBCompletion) WriteCompletion;
  2118.             
  2119. #if MAX_USB_TRANSFER_SIZE
  2120.             //
  2121.             //    the completion routine will queue another BulkWrite until we exhaust the data
  2122.             //        or there is an error which can't be retried
  2123.             //
  2124.             if ( pb->ioReqCount > MAX_USB_TRANSFER_SIZE )
  2125.                 usbprint->usbReqCount = MAX_USB_TRANSFER_SIZE;
  2126.             else
  2127. #endif
  2128.                 usbprint->usbReqCount = pb->ioReqCount;
  2129.     
  2130.  
  2131. #if DOUBLE_BUFFER
  2132.             //
  2133.             //    make sure we have enough room in our buffer
  2134.             //    then copy the user data into our page aligned buffer
  2135.             //
  2136.             if ( usbprint->usbReqCount > pPrinterPB->pageWriteAlignedBufferSize )
  2137.                 usbprint->usbReqCount = pPrinterPB->pageWriteAlignedBufferSize;
  2138.             BlockCopy( usbprint->usbBuffer, pPrinterPB->pageWriteAlignedBuffer, usbprint->usbReqCount );
  2139.             usbprint->usbBuffer = pPrinterPB->pageWriteAlignedBuffer;
  2140. #endif
  2141.             pb->ioResult = ioInProgress;
  2142.     
  2143. #if LOCK_MEMORY
  2144.             err = LockMemory( usbprint->usbBuffer, usbprint->usbReqCount );
  2145.             IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"QueueWrite LockMem failed" ) );
  2146.             if ( err == noErr )
  2147. #endif
  2148.                 err = SafeUSBBulkWrite( usbprint );
  2149.             if ( immediateError(err) )
  2150.             {
  2151.                 MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Immediate error doing bulk write",0 );
  2152.                 IF_DEBUG( DebugStr( USBStatusStr(err, kPString) ) );
  2153.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2154.                 pb->ioResult = err;
  2155.             }
  2156.             //
  2157.             //    note our logging is one write for each the client request
  2158.             //        not one write for each usb transaction
  2159.             //
  2160.             LOGGING( fwrite( pb->ioBuffer, sizeof(char), pb->ioReqCount, logfile ) );
  2161.         }
  2162.         else
  2163.         {
  2164.             MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Write to unopened pipe" , usbprint->usbStatus );
  2165.             pb->ioResult = abortErr;
  2166.         }
  2167.     }
  2168. }
  2169.  
  2170.  
  2171. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2172.     Name:        Abort
  2173.  
  2174.     Input Parameters:    
  2175.         refNum            DRVR refnum
  2176.         pPrinterPB        current printing device class's storage
  2177.  
  2178.     Output Parameters:
  2179.         
  2180.     Description:
  2181.         Asynchronous completion.
  2182.         Note: USBAbortPipeByReference can leave the data toggle in the wrong state.
  2183.                 We need to abort both pipes, and then the client must soft reset the printer
  2184.                 to get the printer's data toggles correct.
  2185.         We prematurely call completion routines for active i/o so that CloseDriverSync
  2186.             will not hang the system after an abort, including hot unplug. This works out okay,
  2187.             since the request will be dequeued now, and when the i/o actually terminates
  2188.             the system will be called with an invalid queue element and then reject this second
  2189.             attempt to dequeue the i/o.
  2190.  
  2191.  
  2192.  
  2193.  
  2194. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2195. OSStatus
  2196. Abort( DriverRefNum refNum, struct usbPrinterPBStruct *pPrinterPB )
  2197. {
  2198.     OSStatus        err = noErr;
  2199.  
  2200.     //
  2201.     //    if there's any pending io this will call the completion routine
  2202.     //
  2203.     MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called" , 0);
  2204.     if (refNum == pPrinterPB->outRefNum)
  2205.     {
  2206.         MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called on out pipe" , 0);
  2207.         if ( pPrinterPB->in.usbCompletion != (USBCompletion) NULL )
  2208.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "***** Abort with write in progress" , 0);
  2209.         
  2210.         err = USBAbortPipeByReference( pPrinterPB->writePipeRef );
  2211.         err = USBClearPipeStallByReference( pPrinterPB->writePipeRef );
  2212.         
  2213.         if ( pPrinterPB->out.usbCompletion != (USBCompletion) NULL )
  2214.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, abortErr, pPrinterPB->writeDrvr.pb, pPrinterPB->writeDrvr.ctl ); 
  2215.     }
  2216.     
  2217.     if (refNum == pPrinterPB->inRefNum)
  2218.     {
  2219.         MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called on in pipe" , 0);
  2220.         if ( pPrinterPB->out.usbCompletion != (USBCompletion) NULL )
  2221.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "***** Abort with read in progress" , 0);
  2222.  
  2223.         err = USBAbortPipeByReference( pPrinterPB->readPipeRef );
  2224.         err = USBClearPipeStallByReference( pPrinterPB->readPipeRef );
  2225.  
  2226.         if ( pPrinterPB->in.usbCompletion != (USBCompletion) NULL )
  2227.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, abortErr, pPrinterPB->readDrvr.pb, pPrinterPB->readDrvr.ctl ); 
  2228.     }
  2229.     return err;
  2230. }
  2231.  
  2232.  
  2233. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2234.     Name:        CompletionProc
  2235.  
  2236.     Input Parameters:    
  2237.         pb                    USB param block ptr
  2238.     
  2239.     Output Parameters:
  2240.         
  2241.     Description:
  2242.         Asynchronous completion routine for DRVR requests.
  2243.  
  2244.  
  2245.  
  2246.  
  2247.  
  2248. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2249. static void 
  2250. CompletionProc(USBPB *pb)
  2251. {
  2252.     //    call the user completion routine
  2253.     struct usbPrinterPBStruct
  2254.                     *pPrinterPB = (struct usbPrinterPBStruct    *) pb->usbRefcon;
  2255.     IOParamPtr     clientParam = pPrinterPB->statusDrvr.pb;
  2256.  
  2257.     clientParam->ioActCount = pb->usbActCount;
  2258.  
  2259.     if ( pb->usbStatus != noErr ) 
  2260.     {
  2261.         USBClearPipeStallByReference(pb->usbReference);  // we got an error, try to clear any stalls
  2262.  
  2263.         IF_DEBUG( MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "CompletionProc Error" , pb->usbStatus ) );
  2264.         IF_DEBUG( MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, USBStatusStr(pb->usbStatus, kPString) , pb->usbStatus ) );
  2265.     }
  2266.  
  2267.     pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2268.     if ( pPrinterPB->statusDrvr.ctl != NULL )
  2269.         CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, pPrinterPB->statusDrvr.ctl ); 
  2270. }
  2271.  
  2272. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2273.     Name:        CentronicsStatus
  2274.  
  2275.     Input Parameters:    
  2276.         pb                        MacOS device manager parameter block
  2277.         ctl                    device manager dCtl block
  2278.         pPrinterPB            current printing device class's storage
  2279.  
  2280.     Output Parameters:
  2281.         pStatusByte        
  2282.         
  2283.     Description:
  2284.         setup the device request for a USB printer class request one byte status.
  2285.  
  2286.  
  2287.  
  2288.  
  2289.  
  2290. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2291. static void
  2292. CentronicsStatus( USBPB *usbprint, Ptr buffer, short interfaceNumber )
  2293. {
  2294.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  2295.  
  2296.     usbprint->usb.cntl.BRequest = kUSBPrintClassGetCentronicsStatus;
  2297.     usbprint->usb.cntl.WValue = 0;
  2298.     usbprint->usb.cntl.WIndex = interfaceNumber;
  2299.  
  2300.     usbprint->usbReqCount = 1;
  2301.     usbprint->usbBuffer = buffer;
  2302. }
  2303.  
  2304. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2305.     Name:        ClearEndpointHalt
  2306.  
  2307.     Input Parameters:    
  2308.         usbprint                USB param block
  2309.  
  2310.     Output Parameters:
  2311.         
  2312.     Description:
  2313.         Setup the device request for a USB clear endpoint halt.
  2314.  
  2315. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2316. void
  2317. ClearEndpointHalt( USBPB *usbprint)
  2318. {
  2319.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBStandard, kUSBEndpoint);
  2320.  
  2321.     usbprint->usb.cntl.BRequest = kUSBRqClearFeature;
  2322.     usbprint->usb.cntl.WValue = kUSBFeatureEndpointStall;
  2323.     usbprint->usbFlags = kUSBAddressRequest;
  2324.  
  2325.     usbprint->usbReqCount = 0;
  2326.     usbprint->usbBuffer = NULL;
  2327.     
  2328.  
  2329. }
  2330.  
  2331. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2332.     Name:        SoftReset
  2333.  
  2334.     Input Parameters:    
  2335.         usbprint                USB param block
  2336.         interfaceNumber
  2337.  
  2338.     Output Parameters:
  2339.         
  2340.     Description:
  2341.         Setup the device request for a USB printer class request soft reset.
  2342.  
  2343.  
  2344.  
  2345.  
  2346.  
  2347. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2348. void
  2349. SoftReset( USBPB *usbprint, short interfaceNumber )
  2350. {
  2351.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBClass, kUSBOther);
  2352.  
  2353.     usbprint->usb.cntl.BRequest = kUSBPrintClassSoftReset;
  2354.     usbprint->usb.cntl.WValue = 0;
  2355.     usbprint->usb.cntl.WIndex = interfaceNumber;
  2356.  
  2357.     usbprint->usbReqCount = 0;
  2358.     usbprint->usbBuffer = NULL;
  2359.     
  2360.  
  2361. }
  2362.  
  2363. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2364.     Name:        CapabilityRequest
  2365.  
  2366.     Input Parameters:    
  2367.         usbprint            USB parameter block
  2368.         p                    result pointer
  2369.         length            amount of data allocated
  2370.         config
  2371.         interfaceNum
  2372.         alternateSetting
  2373.         
  2374.  
  2375.     Output Parameters:
  2376.         p                    result pointer
  2377.         length            amount of data allocated
  2378.         
  2379.     Description:
  2380.         setup the device request for a USB printer class request 1284 id string.
  2381.  
  2382.  
  2383.  
  2384.  
  2385.  
  2386. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2387. void
  2388. CapabilityRequest( USBPB *pb, Ptr p, long length, short configValue, short interfaceNumber, short alternateSetting  )
  2389. {
  2390.  
  2391.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  2392.  
  2393.     pb->usb.cntl.BRequest = kUSBPrintClassGetDeviceID;
  2394.     pb->usb.cntl.WValue = configValue;        // configuration
  2395.     pb->usb.cntl.WIndex = (interfaceNumber<<8) | alternateSetting;
  2396.  
  2397.     pb->usbReqCount = length;
  2398.     pb->usbBuffer = p;
  2399.  
  2400. }
  2401.  
  2402. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2403.     Name:        StatusControlRequests
  2404.  
  2405.     Input Parameters:    
  2406.         pb                        MacOS device manager parameter block
  2407.         ctl                    device manager dCtl block
  2408.         pPrinterPB            current printing device class's storage
  2409.  
  2410.     Output Parameters:
  2411.         
  2412.     Description:
  2413.         Asynchronous completion.
  2414.  
  2415.  
  2416.  
  2417.  
  2418. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2419.  
  2420. void
  2421. ControlStatusRequests( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  2422. {
  2423.  
  2424.     //
  2425.     //    queue a transaction to retrieve the centronics status
  2426.     //
  2427.     OSStatus    err;
  2428.     USBPB        *usbprint = &pPrinterPB->pb;
  2429.     Boolean        dosomething = false;
  2430.     
  2431. #if DEBUG
  2432.     Str255        text;
  2433.  
  2434.     sprintf( (char *)text, " PrinterClass ControlStatus: %d", ((CntrlParam *) pb)->csCode );
  2435.     text[0] = CStrLen((char *)text); // c2pstr
  2436.     MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2437. #endif
  2438.  
  2439.  
  2440.  
  2441.     if (pPrinterPB->terminating)
  2442.     {
  2443.         pb->ioResult = abortErr;
  2444.     }
  2445.     else
  2446.     {
  2447.         switch( ((CntrlParam *) pb)->csCode )
  2448.         {
  2449.         case kDrvrCentronicsStatus:
  2450.             dosomething = true;
  2451.             CentronicsStatus( usbprint,  *((Ptr *)((CntrlParam *) pb)->csParam), pPrinterPB->interfaceNumber );
  2452.             SetNullUSBParamBlock(pPrinterPB->deviceRef,  usbprint );
  2453.             break;
  2454.             
  2455.             
  2456.         case kDrvr1284IdString:
  2457.             dosomething = true;
  2458.             CapabilityRequest( usbprint,
  2459.                                     *((Ptr *)((CntrlParam *) pb)->csParam),
  2460.                                     *((long *) &((CntrlParam *) pb)->csParam[4]),
  2461.                                     0,        // configuration
  2462.                                     pPrinterPB->interfaceNumber,
  2463.                                     pPrinterPB->alternateSetting);
  2464.             SetNullUSBParamBlock(pPrinterPB->deviceRef,  usbprint );
  2465.             break;
  2466.             
  2467.         case kDrvrSoftReset:
  2468.             dosomething = true;
  2469.             if ( ((CntrlParam *) pb)->ioCRefNum == pPrinterPB->outRefNum )
  2470.             {
  2471.                 SetNullUSBParamBlock(pPrinterPB->writePipeRef,  usbprint );
  2472.             }
  2473.             else 
  2474.             {
  2475.                 SetNullUSBParamBlock(pPrinterPB->readPipeRef,  usbprint );
  2476.             }
  2477.             ClearEndpointHalt( usbprint );
  2478.             break;
  2479.         
  2480.         case kDrvrPrivateLog:
  2481.             // BT - 15Jun99, print a message in the log for the 68k code.
  2482.             MyUSBExpertStatusLevel(((CntrlParam *) pb)->csParam[2], pPrinterPB->deviceRef, *(unsigned char **)(((CntrlParam *) pb)->csParam), *((long *)&((CntrlParam *) pb)->csParam[4]) );
  2483.             return;
  2484.             break;
  2485.         
  2486.         case kDrvrPrivateOpnClose:
  2487.             if (gUSBVersion >= kUSBv135)
  2488.             {
  2489.                 // BT - 15Jun99, Open or close has been called, arrange for suspend or resume.
  2490.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB print driver kDrvrPrivateOpnClose", ((CntrlParam *) pb)->csParam[0] == 0);
  2491.                 // If csParam[0] is 1 we're being opened, if 0 we're being closed
  2492.                 if(((CntrlParam *) pb)->csParam[0] == 1)
  2493.                 {
  2494.                     openRef++;
  2495.                     wantToBe = kUSBPrintResumed;
  2496.                     // We're being opened
  2497.                 }
  2498.                 else if(((CntrlParam *) pb)->csParam[0] == 0)
  2499.                 {
  2500.                     if (--openRef < 0) 
  2501.                         openRef = 0;
  2502.                     
  2503.                     if (!openRef)  // is this the last close?
  2504.                         wantToBe = kUSBPrintSuspended;
  2505.                     else
  2506.                         wantToBe = kUSBPrintResumed;
  2507.                 }
  2508.                 else
  2509.                 {
  2510.                     MyUSBExpertStatusLevel(2, pPrinterPB->deviceRef, "\pUSB print driver kDrvrPrivateOpnClose unknown message", ((CntrlParam *) pb)->csParam[0] == 0);
  2511.                 }
  2512.                 USBPrintDoSuspendResume(pPrinterPB->interfaceRef);
  2513.             }
  2514.             return;
  2515.             break;
  2516.         default:
  2517.             break;
  2518.         }
  2519.     
  2520.         if ( !dosomething )
  2521.             pb->ioResult = paramErr;
  2522.         else
  2523.         {
  2524.             // BT - 15Jun99, if we're not currently awake, delay this until we are.
  2525.             if(currentlyAre == kUSBPrintSuspended )
  2526.             {
  2527.                 
  2528.                 if (Cpb != nil){
  2529.                     pb->ioResult = notOpenErr;
  2530.                     MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, Can't support more than one delayed control call while suspended!", pb->ioResult );
  2531.                     return;
  2532.                 }
  2533.                     
  2534.                 pb->ioResult = ioInProgress;
  2535.                 MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, delaying control for resume", 0 );
  2536.                 CpPrinterPB = pPrinterPB;
  2537.                 Cctl = ctl;
  2538.                 Cpb = pb;
  2539.                 if( (currentlyAre != kUSBPrintSuspended) && (Rpb != nil) )
  2540.                 {
  2541.                     MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, resumed while we wern't looking", 0 );
  2542.                     // resumed and executed this while we were doing this.
  2543.                     return;
  2544.                 }
  2545.                 else
  2546.                 {
  2547.                     // now wait for resume to happen
  2548.                     MyUSBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, let resume take over", 0 );
  2549.                     return;
  2550.                 }        
  2551.             }
  2552.  
  2553.             usbprint->usbActCount = 0;
  2554.             usbprint->usbCompletion = (USBCompletion)CompletionProc;
  2555.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  2556.         
  2557.             pb->ioResult = ioInProgress;
  2558.             pPrinterPB->statusDrvr.pb = pb;
  2559.             pPrinterPB->statusDrvr.ctl = ctl;
  2560.         
  2561.             err = USBDeviceRequest(usbprint);
  2562.             if(immediateError(err))
  2563.             {
  2564.                 USBExpertFatalError(usbprint->usbReference, err, kPStrPrinterDriverName"StatusControlRequests", 0);
  2565.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2566.                 pb->ioResult = err;
  2567.             }
  2568.         }
  2569.     }
  2570. }
  2571.  
  2572.  
  2573. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2574.     Name:        PrinterDeviceCompletionProc
  2575.  
  2576.     Input Parameters:    
  2577.         pb                refCon tells which state we're completing
  2578.  
  2579.     Output Parameters:
  2580.         <none>
  2581.         
  2582.     Description:
  2583.         Complete asynch transactions initiated by PrinterDeviceInitiateTransaction.
  2584.  
  2585.  
  2586.  
  2587.  
  2588.  
  2589.  
  2590.  
  2591.  
  2592.  
  2593.  
  2594. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2595.  
  2596. static void 
  2597. PrinterDeviceCompletionProc(USBPB *pb)
  2598. {
  2599. Str255        tempstr1,tempstr2;
  2600. register     struct usbPrinterPBStruct *pPrinterPB;
  2601. OSStatus    err;
  2602. UInt32        i = 0;
  2603.     
  2604.     
  2605.     pPrinterPB = (struct usbPrinterPBStruct *)(pb);
  2606.  
  2607.     pPrinterPB->transDepth--; 
  2608.     if ((pPrinterPB->transDepth < 0) || (pPrinterPB->transDepth > 1))
  2609.     {
  2610.         USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName "CompletionProc Illegal Transaction Depth", pPrinterPB->transDepth );
  2611.     }
  2612.  
  2613.     MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, StateStr(pPrinterPB->pb.usbRefcon, kPString) , pPrinterPB->pb.usbStatus );
  2614.  
  2615.     pPrinterPB->delayInProgress = false;
  2616.     
  2617.     if ( pPrinterPB->terminating )
  2618.     {
  2619.         //    if we've been hot unplugged
  2620.         //        don't startup any new transactions
  2621.         //     allow PrintDriverFinalize to continue
  2622.         pPrinterPB->pb.usbStatus = kUSBAbortedError;
  2623.         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2624.     }
  2625.     
  2626.  
  2627.     switch( pPrinterPB->pb.usbStatus )
  2628.     {
  2629.         case kUSBPending:
  2630.         case noErr:
  2631.             pPrinterPB->pb.usbRefcon &= ~kRetryTransaction;
  2632.             pPrinterPB->retryCount = kPrinterRetryCount;
  2633.             break;
  2634.             
  2635.         case kUSBLinkErr:
  2636.         case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  2637.         case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  2638.         case kUSBDataToggleErr:                            /*  Pipe stall, Bad data toggle */
  2639.         case kUSBNotRespondingErr:                        /*  Pipe stall, No device, device hung */
  2640.         case kUSBPIDCheckErr:                            /*  Pipe stall, PID CRC error */
  2641.         case kUSBWrongPIDErr:                            /*  Pipe stall, Bad or wrong PID */
  2642.         case kUSBTimedOut:                                /* Transaction timed out. */
  2643.         default:
  2644.         
  2645.             USBClearPipeStallByReference(pPrinterPB->deviceRef);  // we got an error, try to clear any stalls
  2646.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "    retry", pPrinterPB->pb.usbStatus);
  2647.             
  2648.             // clear out the transaction pending flag
  2649.             pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2650.             pPrinterPB->pb.usbRefcon |= kRetryTransaction;
  2651.             pPrinterPB->retryCount--;
  2652.             if (!pPrinterPB->retryCount)
  2653.             {
  2654.                 USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName "Retry failed", pPrinterPB->pb.usbRefcon & ~kRetryTransaction);
  2655.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2656.             } 
  2657.             else 
  2658.             {
  2659.                 pPrinterPB->pb.usbStatus = noErr;             // let's retry one more time
  2660.             }
  2661.             break;
  2662.             
  2663.         case kUSBNotFound:
  2664.             break;
  2665.             
  2666.         case kUSBAbortedError:                        /* user cancel, or hot unplug */
  2667.             // clear out the transaction pending flag
  2668.             pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;
  2669.             pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2670.             pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2671.             break;
  2672.     }
  2673.  
  2674.     if (pPrinterPB->pb.usbRefcon & kTransactionPending)             
  2675.     {            
  2676.         short    length;
  2677.     
  2678.         //
  2679.         //    advance to the next state
  2680.         //
  2681.         pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2682.         switch(pPrinterPB->pb.usbRefcon)
  2683.         {
  2684.             case kFindInterface_bidirectional:
  2685.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_bidirectional completed", pPrinterPB->pb.usb.cntl.WIndex);
  2686.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2687.                 {
  2688.                     if ((pPrinterPB->pb.usbClassType == kUSBPrintingClass) && 
  2689.                         (pPrinterPB->pb.usbSubclass == kUSBPrinterSubclass) &&
  2690.                         (pPrinterPB->pb.usbProtocol == kUSBPrinterBidirectionalProtocol))
  2691.                     {
  2692.                         MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Found bidirectional interface at alt setting ", pPrinterPB->pb.usbOther);
  2693.                         pPrinterPB->configurationNumber = pPrinterPB->pb.usb.cntl.WValue;
  2694.                         pPrinterPB->alternateSetting = pPrinterPB->pb.usbOther;
  2695.                         pPrinterPB->printerProtocol = kUSBPrinterBidirectionalProtocol;
  2696.                         
  2697.                         // if we started out as a device class driver, then the interface descriptor will be NULL
  2698.                         // this would mean that the device will need to be opened before anything can be done with it
  2699.                         // if the interface descriptor point isn't null, then we started as an interface driver,
  2700.                         // so just skip by the opendevice call
  2701.                         if (pPrinterPB->pInterfaceDescriptor != NULL)
  2702.                         {
  2703.                         // did we find the interface we were looking for?
  2704.                             if (pPrinterPB->interfaceNumber == pPrinterPB->pb.usb.cntl.WIndex)
  2705.                             {
  2706.                                 pPrinterPB->pb.usbRefcon = kSetInterface;
  2707.                             }
  2708.                             else
  2709.                             {
  2710.                                 USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_Bidirectional didn't find the right interface", 0);
  2711.                             }
  2712.                         }
  2713.                         else
  2714.                         {
  2715.                             pPrinterPB->pb.usbRefcon = kOpenDevice;
  2716.                             pPrinterPB->interfaceNumber = pPrinterPB->pb.usb.cntl.WIndex;
  2717.                         }
  2718.                     }
  2719.                 }
  2720.                 else
  2721.                 {
  2722.                     if ( pPrinterPB->pb.usbStatus == kUSBNotFound )
  2723.                     {
  2724.                         MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Bidirectional interface was not found", pPrinterPB->pb.usb.cntl.WIndex);
  2725.                         pPrinterPB->pb.usbRefcon = kFindInterface_unidirectional;
  2726.                         pPrinterPB->pb.usbStatus = noErr;  // must clear error for state machine to continue <USB46>
  2727.                     }
  2728.                     else
  2729.                     {
  2730.                         USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_bidirectional failed", 0);
  2731.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2732.                     }
  2733.                 }
  2734.                 break;
  2735.                 
  2736.             case kFindInterface_unidirectional:
  2737.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_unidirectional completed", pPrinterPB->pb.usb.cntl.WIndex);
  2738.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2739.                 {
  2740.                     if ((pPrinterPB->pb.usbClassType == kUSBPrintingClass) && 
  2741.                         (pPrinterPB->pb.usbSubclass == kUSBPrinterSubclass) &&
  2742.                         (pPrinterPB->pb.usbProtocol == kUSBPrinterUnidirectionalProtocol))
  2743.                     {
  2744.                         MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Found unidirection interface at alt setting ", pPrinterPB->pb.usbOther);
  2745.                         pPrinterPB->pb.usbRefcon = kOpenDevice;
  2746.                         pPrinterPB->configurationNumber = pPrinterPB->pb.usb.cntl.WValue;
  2747.                         pPrinterPB->alternateSetting = pPrinterPB->pb.usbOther;
  2748.                         pPrinterPB->printerProtocol = kUSBPrinterUnidirectionalProtocol;
  2749.                         // if we started out as a device class driver, then the interface descriptor will be NULL
  2750.                         // this would mean that the device will need to be opened before anything can be done with it
  2751.                         // if the interface descriptor point isn't null, then we started as an interface driver,
  2752.                         // so just skip by the opendevice call
  2753.                         if (pPrinterPB->pInterfaceDescriptor)
  2754.                         {
  2755.                             if (pPrinterPB->interfaceNumber == pPrinterPB->pb.usb.cntl.WIndex)
  2756.                             {
  2757.                                 pPrinterPB->pb.usbRefcon = kSetInterface;
  2758.                             }
  2759.                             else
  2760.                             {
  2761.                                 USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_Unidirectional didn't find the right interface", 0);
  2762.                             }
  2763.                         }
  2764.                         else
  2765.                         {
  2766.                             pPrinterPB->pb.usbRefcon = kOpenDevice;
  2767.                             pPrinterPB->interfaceNumber = pPrinterPB->pb.usb.cntl.WIndex;
  2768.                         }
  2769.                     }
  2770.                 }
  2771.                 else
  2772.                 {
  2773.                     if ( pPrinterPB->pb.usbStatus == kUSBNotFound )
  2774.                     {
  2775.                         MyUSBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Unidirectional interface was not found", pPrinterPB->pb.usb.cntl.WIndex);
  2776.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2777.                     }
  2778.                     else
  2779.                     {
  2780.                         USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_unidirectional failed", 0);
  2781.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2782.                     }
  2783.                 }
  2784.                 break;
  2785.                 
  2786.             case kOpenDevice:
  2787.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2788.                 {
  2789.                     MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kOpenDevice completed", pPrinterPB->pb.usbStatus);
  2790.                     pPrinterPB->pb.usbRefcon = kNewInterfaceRef;
  2791.                 }
  2792.                 else
  2793.                 {
  2794.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kOpenDevice failed", 0);
  2795.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2796.                 }
  2797.                 break;
  2798.                 
  2799.             case kNewInterfaceRef:
  2800.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kNewInterfaceRef completed", pPrinterPB->pb.usbReference);
  2801.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2802.                 {
  2803.                     pPrinterPB->interfaceRef = pPrinterPB->pb.usbReference;
  2804.                     pPrinterPB->pb.usbRefcon = kSetInterface;
  2805.                 }
  2806.                 else
  2807.                 {
  2808.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kNewInterfaceRef failed", 0);
  2809.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2810.                 }
  2811.                 break;
  2812.             
  2813.             case kSetInterface:
  2814.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kSetInterface completed", 0);
  2815.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2816.                 {
  2817.                     pPrinterPB->pb.usbRefcon = kConfigureInterface;
  2818.                 }
  2819.                 else
  2820.                 {
  2821.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kSetInterface failed", 0);
  2822.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2823.                 }
  2824.                 break;
  2825.             
  2826.             case kConfigureInterface:
  2827.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kConfigureInterface completed, pipes = ", pPrinterPB->pb.usbOther);
  2828.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2829.                 {
  2830.                     pPrinterPB->pipeCount = pPrinterPB->pb.usbOther;
  2831.                     pPrinterPB->pb.usbRefcon = kGetCapabilityString;
  2832.                 }
  2833.                 else
  2834.                 {
  2835.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kConfigureInterface failed", 0);
  2836.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2837.                 }
  2838.                 break;
  2839.             
  2840.             case kGetCapabilityString:
  2841.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCapabilityString completed", pPrinterPB->pb.usbStatus);
  2842.                 
  2843.                 if ( pPrinterPB->pb.usbActCount >= 2 )
  2844.                 {
  2845.                     length = pPrinterPB->pCapabilityString[1] | (pPrinterPB->pCapabilityString[0] << 8);
  2846.                 }
  2847.                 else
  2848.                 {
  2849.                     length = 0;
  2850.                 }
  2851.     
  2852.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2853.                 {
  2854.                     //
  2855.                     //    In the short term (fall '98) several vendors are planning on shipping 
  2856.                     //        devices with a parallel port and using the Lucent USS-720 USB-to-parallel hardware.
  2857.                     //    Unfortunately this isn't an ideal solution from the USB perspective:
  2858.                     //        users can leave the printer off while the cable responds that there's
  2859.                     //        a printer connected. Then we have no way of using the DEVICE_ID
  2860.                     //        string to tag the printer and register it.
  2861.                     //    To alleviate this situation, we repeatedly poll the USS-720 if the DEVICE_ID
  2862.                     //        string is null. Every few seconds we'll retry this state.
  2863.                     //    At some point the user wants to print and switches on the printer. The class
  2864.                     //    driver then picks up from here and registers the device properly.
  2865.                     //
  2866.                     
  2867.                     if ( pPrinterPB->pb.usbActCount == 0 )
  2868.                         pPrinterPB->pb.usbRefcon = kDelayGetCapability;
  2869.                     else
  2870.                         pPrinterPB->pb.usbRefcon = kFindBulkOutPipe;
  2871.                 }
  2872.                 else
  2873.                 {
  2874.                     if ( pPrinterPB->pb.usbStatus == kUSBOverRunErr )
  2875.                     {
  2876.                         //
  2877.                         //    if we've haven't managed to read the whole capability string
  2878.                         //        we need to allocate memory and read it in by initiating kGetFullCapabilityString
  2879.                         //
  2880.     
  2881.                         if ( length > sizeof(pPrinterPB->capability) && pPrinterPB->pb.usbRefcon == kGetCapabilityString )
  2882.                         {
  2883.                             pPrinterPB->pb.usbRefcon = kAllocateCapabilityMem;
  2884.                             pPrinterPB->pb.usbStatus = noErr;  // must clear error for state machine to continue <USB46>
  2885.                             break;                               // advance to that state <USB46>
  2886.                         }    
  2887.                         
  2888.                 
  2889.                     }
  2890.                     else
  2891.                     {
  2892.                         USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetCapabilityString failed", 0);
  2893.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2894.                     }
  2895.                 }
  2896.                 
  2897.                 // write the capability string to the log
  2898.                 if ((pPrinterPB->pb.usbStatus == kUSBOverRunErr)  || (pPrinterPB->pb.usbStatus == noErr))
  2899.                 {
  2900.                     if (length > 2)                     // is there a valid string? (length more than 2 bytes)
  2901.                     {
  2902.                         length -= 2;
  2903.                         if (length > 200)                // cut the string off at 200 characters
  2904.                             length = 200;
  2905.                             
  2906.                         BlockMove( (Ptr)&(pPrinterPB->pCapabilityString[2]), (Ptr)tempstr2, length);
  2907.                         tempstr2[length] = '\0';        // mark the end of the cstring
  2908.                         
  2909.                         sprintf( (char *)tempstr1, (char const *) kCStrPrinterDriverName"1284 Capability String: %s", tempstr2 );
  2910.                         CStrToPStr( (unsigned char *)tempstr2, (char *)tempstr1);    // convert it to a pstring
  2911.                     }
  2912.                     else
  2913.                     {
  2914.                         CStrToPStr( (unsigned char *)tempstr2, (char *) kCStrPrinterDriverName"Capability string is empty!!" );
  2915.                     }
  2916.                     MyUSBExpertStatusLevel(kNormalStatusLevel,  pPrinterPB->deviceRef, tempstr2, length);
  2917.                 }
  2918.                 break;
  2919.                 
  2920.             case kDelayGetCapability:
  2921.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kDelayGetCapability completed", pPrinterPB->pb.usbStatus);
  2922.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2923.                 {
  2924.                     pPrinterPB->pb.usbRefcon = kGetCapabilityString;
  2925.                 }
  2926.                 else
  2927.                 {
  2928.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kDelayGetCapability failed", 0);
  2929.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2930.                 }
  2931.                 break;
  2932.                 
  2933.             case kAllocateCapabilityMem:
  2934.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kAllocateCapabilityMem completed", pPrinterPB->pb.usbStatus);
  2935.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2936.                 {
  2937.                     pPrinterPB->pCapabilityString = pPrinterPB->pb.usbBuffer;
  2938.                     pPrinterPB->pb.usbRefcon = kGetFullCapabilityString;    
  2939.                 }
  2940.                 else
  2941.                 {
  2942.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kAllocateCapabilityMem failed", 0);
  2943.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2944.                 }
  2945.                 break;
  2946.             
  2947.             case kGetFullCapabilityString:
  2948.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetFullCapabilityString completed", pPrinterPB->pb.usbStatus);
  2949.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2950.                 {
  2951.                     pPrinterPB->pb.usbRefcon = kGetInterface;
  2952.                 }
  2953.                 else
  2954.                 {
  2955.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetFullCapabilityString failed", 0);
  2956.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2957.                 }
  2958.                 break;
  2959.                 
  2960.             case kGetInterface:
  2961.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetInterface completed", pPrinterPB->pb.usbStatus);
  2962.                 if (( pPrinterPB->pb.usbStatus == noErr ) && (pPrinterPB->whichAltInterface == pPrinterPB->alternateSetting))
  2963.                 {
  2964.                     pPrinterPB->pb.usbRefcon = kFindBulkOutPipe;
  2965.                 }
  2966.                 else
  2967.                 {
  2968.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetInterface - wrong interface selected", pPrinterPB->whichAltInterface);
  2969.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2970.                 }
  2971.                 break;
  2972.  
  2973.             case kFindBulkOutPipe:
  2974.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkOutPipe completed", pPrinterPB->pb.usbReference);
  2975.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2976.                 {
  2977.                     pPrinterPB->writePipeRef = pPrinterPB->pb.usbReference;             // remember the ref
  2978.                     pPrinterPB->out = pPrinterPB->pb;                                    // copy the paramblock
  2979.                     pPrinterPB->out.usbCompletion =  (USBCompletion) NULL;                // for finalize
  2980.  
  2981.                     if ( pPrinterPB->printerProtocol == kUSBPrinterBidirectionalProtocol )
  2982.                         pPrinterPB->pb.usbRefcon = kFindBulkInPipe;
  2983.                     else
  2984.                         pPrinterPB->pb.usbRefcon = kTaskTimeRequired;
  2985.                 }
  2986.                 else
  2987.                 {
  2988.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindBulkOutPipe failed", 0);
  2989.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2990.                 }
  2991.                 break;
  2992.                 
  2993.             case kFindBulkInPipe:
  2994.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkInPipe completed", pPrinterPB->pb.usbReference);
  2995.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2996.                 {
  2997.                     pPrinterPB->readPipeRef = pPrinterPB->pb.usbReference;
  2998.                     pPrinterPB->in = pPrinterPB->pb;                                    // copy the paramblock
  2999.                     pPrinterPB->in.usbCompletion =  (USBCompletion) NULL;                // for finalize
  3000.  
  3001.                     pPrinterPB->pb.usbRefcon = kTaskTimeRequired;
  3002.                 }
  3003.                 else
  3004.                 {
  3005.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindBulkInPipe failed", 0);
  3006.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3007.                 }
  3008.                 break;
  3009.                 
  3010.             case kTaskTimeRequired:
  3011.                 MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired completed (now at task time)", pPrinterPB->pb.usbReference);
  3012.             //
  3013.             //    once we know what device we're dealing with
  3014.             //        open the i/o channel(s) to the device
  3015.             //        and enter it in the name registry
  3016.             //
  3017.                 
  3018.                 err = InstallDrivers( pPrinterPB );
  3019.                 if ( err == noErr )
  3020.                 {
  3021.                     MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired - drivers installed", pPrinterPB->pb.usbReference);
  3022.                     err = RegisterDevice( pPrinterPB );
  3023.                     if ( err == noErr )
  3024.                     {
  3025.                         MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired - RegisterDevice successful", pPrinterPB->pb.usbReference);
  3026.                     }
  3027.                     else
  3028.                     {
  3029.                         USBExpertFatalError(pPrinterPB->interfaceRef, err, kPStrPrinterDriverName"kTaskTimeRequired - RegisterDevice failed", 0);
  3030.                     }
  3031.                 }
  3032.                 else
  3033.                 {
  3034.                     USBExpertFatalError(pPrinterPB->interfaceRef, err, kPStrPrinterDriverName"kTaskTimeRequired - InstallDrivers failed", 0);
  3035.                 }
  3036.     
  3037.                 pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;                    // Finalize
  3038.                 if ( pPrinterPB->pb.usbStatus == noErr )
  3039.                 {
  3040.                     MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, "\pPrinter driver now exiting setup, calling suspend", pPrinterPB->interfaceRef );
  3041.                     USBPrintDoSuspendResume(pPrinterPB->interfaceRef); 
  3042.                     pPrinterPB->pb.usbRefcon = kReturnFromDriver;
  3043.                     pPrinterPB->printerConfigured = true;
  3044.                 }
  3045.                 else
  3046.                 {
  3047.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"RegisterDevice failed", 0);
  3048.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3049.                 }
  3050.                 break;
  3051.                 
  3052.             case kGetCentronicsStatus:
  3053.                 //
  3054.                 //    if InitiateTransaction fell through on it's kTaskTimeRequired case we'll end up here
  3055.                 //
  3056.                 if ( pPrinterPB->pb.usbStatus == noErr )
  3057.                 {
  3058.                     unsigned char text[255];
  3059.                     sprintf( (char *)text, " Centronics Status: 0x%02x", pPrinterPB->centronics.b );
  3060.                     text[0] = CStrLen((char *)text); // c2pstr
  3061.                     MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, text, pb->usbStatus );
  3062.                     
  3063. #if DEBUG
  3064.                     if ( !pPrinterPB->centronics.status.notError )
  3065.                     {
  3066.                         MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"Error at printer", pPrinterPB->pb.usbStatus);
  3067.                     }
  3068.                     if ( pPrinterPB->centronics.status.paperError )
  3069.                     {
  3070.                         MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"Check paper", pPrinterPB->pb.usbStatus);
  3071.                     }
  3072.                     if ( !pPrinterPB->centronics.status.select )
  3073.                     {
  3074.                         MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"printer offline", pPrinterPB->pb.usbStatus);
  3075.                     }
  3076. #endif
  3077.                     pPrinterPB->pb.usbRefcon = kDelayGetCentronicsStatus;
  3078.                 }
  3079.                 else
  3080.                 {
  3081.                     MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCentronicsStatus - error getting centronics status", pPrinterPB->pb.usbStatus);
  3082.                 }
  3083.                 break;
  3084.                 
  3085.             case kDelayGetCentronicsStatus:
  3086.                 //
  3087.                 //    loop around continually getting status
  3088.                 //
  3089.                 if ( pPrinterPB->pb.usbStatus == noErr )
  3090.                 {
  3091.                     pPrinterPB->pb.usbRefcon = kGetCentronicsStatus;
  3092.                 }
  3093.                 break;
  3094.             case kNilCompletion:
  3095.             default:
  3096.                 if ( pPrinterPB->pb.usbStatus == noErr )
  3097.                     pPrinterPB->pb.usbRefcon = kUndefined | kReturnFromDriver;
  3098.                 break;
  3099.         }
  3100.     }
  3101.     
  3102.     // did the removal notification get called?  If so, don't start another transaction.  Just exit
  3103.    if (!pPrinterPB->terminating)
  3104.     {
  3105.         if (pPrinterPB->pb.usbStatus == noErr )
  3106.         {
  3107.             if (!(pPrinterPB->pb.usbRefcon & kReturnFromDriver))
  3108.                 PrinterDeviceInitiateTransaction(pb);
  3109.         }
  3110.         else if ( pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  3111.         {
  3112.             USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, StateStr(pPrinterPB->pb.usbRefcon, kPString), pPrinterPB->pb.usbRefcon);
  3113.             USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, USBStatusStr(pPrinterPB->pb.usbStatus, kPString), 0);
  3114.         }
  3115.     }
  3116.     else
  3117.     {
  3118.         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3119.     }
  3120.     
  3121.     // If we're exiting the driver, then make certain the completion routine is set to NULL
  3122.     // this lets the driver removal task know that there's nothing pending.
  3123.     if ( pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  3124.     {
  3125.         pPrinterPB->pb.usbCompletion    = (USBCompletion) NULL;
  3126.     }
  3127. }
  3128.  
  3129. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3130.     Name:        PrinterDeviceInitiateTransaction
  3131.  
  3132.     Input Parameters:    
  3133.         pb            USB parameter block
  3134.         
  3135.     Output Parameters:
  3136.         
  3137.     Description:
  3138.         Since USB transactions are asynchronous we use the refCon field
  3139.         in the parameter block to implement the following logic via a state machine.
  3140.  
  3141.         Start out by getting the device configuration descriptor
  3142.         If the device has more than one printing interface
  3143.             If a bidirectional interface exists
  3144.                 select it
  3145.             Else
  3146.                 select the (mandatory) unidirectional interface
  3147.         Get the (mandatory) 1284 capability string
  3148.         Open pipes to the BulkOut (and optional BulkIn) endpoints
  3149.         Install read and write drivers in the unit table
  3150.         Using information from the capability string
  3151.             enter the printer in the MacOS name registry.
  3152.         
  3153.  
  3154.  
  3155.  
  3156.  
  3157.  
  3158.  
  3159. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3160. void
  3161. PrinterDeviceInitiateTransaction(USBPB *pb)
  3162. {
  3163. register struct usbPrinterPBStruct    *pPrinterPB;
  3164. UInt16        length;
  3165. OSStatus    err;
  3166.  
  3167.     pPrinterPB = (struct usbPrinterPBStruct *)(pb);
  3168.     
  3169.     pPrinterPB->transDepth++;
  3170.     if ((pPrinterPB->transDepth < 0) || (pPrinterPB->transDepth > 1))
  3171.     {
  3172.         USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName"InitiateTransaction illegal transaction depth", 0);
  3173.     }
  3174.     IF_DEBUG( MyUSBExpertStatusLevel(5, pPrinterPB->deviceRef, StateStr(pPrinterPB->pb.usbRefcon, kPString), 0) );     
  3175.     
  3176.     pPrinterPB->delayInProgress = false;
  3177.     switch(pPrinterPB->pb.usbRefcon & ~kRetryTransaction)
  3178.     {
  3179.         case kFindInterface_bidirectional:
  3180.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_bidirectional", 0);
  3181.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3182.             
  3183.             pPrinterPB->pb.usbBuffer = 0;
  3184.             pPrinterPB->pb.usbActCount = 0;
  3185.             pPrinterPB->pb.usbReqCount = 0;
  3186.             pPrinterPB->pb.usb.cntl.WIndex = 0;
  3187.             pPrinterPB->pb.usb.cntl.WValue = 0;
  3188.             pPrinterPB->pb.usbClassType = kUSBPrintingClass;
  3189.             pPrinterPB->pb.usbSubclass = kUSBPrinterSubclass;
  3190.             pPrinterPB->pb.usbProtocol = kUSBPrinterBidirectionalProtocol;
  3191.             
  3192.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3193.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3194.             err = USBFindNextInterface(pb);
  3195.             if(immediateError(err))
  3196.             {
  3197.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kFindInterface_bidirectional - immediate error", err);
  3198.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3199.             }
  3200.             break;
  3201.     
  3202.         case kFindInterface_unidirectional:
  3203.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_unidirectional", 0);
  3204.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3205.             
  3206.             pPrinterPB->pb.usbBuffer = 0;
  3207.             pPrinterPB->pb.usbActCount = 0;
  3208.             pPrinterPB->pb.usbReqCount = 0;
  3209.             pPrinterPB->pb.usb.cntl.WIndex = 0;
  3210.             pPrinterPB->pb.usb.cntl.WValue = 0;
  3211.             pPrinterPB->pb.usbClassType = kUSBPrintingClass;
  3212.             pPrinterPB->pb.usbSubclass = kUSBPrinterSubclass;
  3213.             pPrinterPB->pb.usbProtocol = kUSBPrinterUnidirectionalProtocol;
  3214.             
  3215.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3216.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3217.             err = USBFindNextInterface(pb);
  3218.             if(immediateError(err))
  3219.             {
  3220.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kFindInterface_unidirectional - immediate error", err);
  3221.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3222.             }
  3223.             break;
  3224.     
  3225.         case kOpenDevice:
  3226.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kOpenDevice", 0);
  3227.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3228.             
  3229.             pPrinterPB->pb.usbBuffer = 0;
  3230.             pPrinterPB->pb.usbActCount = 0;
  3231.             pPrinterPB->pb.usbReqCount = 0;
  3232.             pPrinterPB->pb.usb.cntl.WValue = pPrinterPB->configurationNumber;
  3233.             
  3234.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3235.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3236.             err = USBOpenDevice(pb);
  3237.             if(immediateError(err))
  3238.             {
  3239.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBOpenDevice - immediate error", err);
  3240.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3241.             }
  3242.             break;
  3243.             
  3244.         case kNewInterfaceRef:
  3245.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kNewInterfaceRef for interface number", pPrinterPB->interfaceNumber);
  3246.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3247.             
  3248.             pPrinterPB->pb.usbBuffer = 0;
  3249.             pPrinterPB->pb.usbActCount = 0;
  3250.             pPrinterPB->pb.usbReqCount = 0;
  3251.             pPrinterPB->pb.usb.cntl.WIndex = pPrinterPB->interfaceNumber;
  3252.             
  3253.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3254.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3255.             err = USBNewInterfaceRef(pb);
  3256.             if(immediateError(err))
  3257.             {
  3258.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBNewInterfaceRef - immediate error", err);
  3259.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3260.             }
  3261.             break;
  3262.             
  3263.  
  3264.         case kSetInterface:
  3265.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kSetInterface to alternate setting", pPrinterPB->alternateSetting);
  3266.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3267.             
  3268.             pPrinterPB->pb.usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBStandard, kUSBInterface);
  3269.         
  3270.             pPrinterPB->pb.usb.cntl.BRequest = kUSBRqSetInterface;
  3271.             pPrinterPB->pb.usb.cntl.WValue = pPrinterPB->alternateSetting;        // alternate setting
  3272.             pPrinterPB->pb.usb.cntl.WIndex = pPrinterPB->interfaceNumber;        // interface
  3273.         
  3274.             pPrinterPB->pb.usbReqCount = 0;
  3275.             pPrinterPB->pb.usbBuffer = NULL;
  3276.         
  3277.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3278.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3279.             err = USBDeviceRequest(pb);
  3280.             if(immediateError(err))
  3281.             {
  3282.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kSetInterface - immediate error", err);
  3283.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3284.             }
  3285.             break;
  3286.  
  3287.  
  3288.         case kConfigureInterface:
  3289.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kConfigureInterface for alternate setting", pPrinterPB->alternateSetting);
  3290.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3291.             
  3292.             pPrinterPB->pb.usbBuffer = 0;
  3293.             pPrinterPB->pb.usbActCount = 0;
  3294.             pPrinterPB->pb.usbReqCount = 0;
  3295.             pPrinterPB->pb.usbOther = pPrinterPB->alternateSetting;
  3296.             
  3297.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3298.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3299.             err = USBConfigureInterface(pb);
  3300.             if(immediateError(err))
  3301.             {
  3302.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBConfigureInterface - immediate error)", err);
  3303.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3304.             }
  3305.             break;
  3306.             
  3307.         case kGetCapabilityString:
  3308.             //
  3309.             //    once the interface (and alternate) is assinged
  3310.             //        we can retreive the 1284 capability string to see what kind of printer
  3311.             //        is attached
  3312.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCapabilityString", 0);
  3313.             pPrinterPB->pCapabilityString = pPrinterPB->capability;
  3314.             
  3315.             GetCapability( pPrinterPB, pPrinterPB->pCapabilityString, sizeof(pPrinterPB->capability) );
  3316.             break;
  3317.             
  3318.         case kDelayGetCapability:
  3319.             //
  3320.             //    USS-720 USB-parallel cable: couldn't get the capability string because the printer is off
  3321.             //        Delay a few seconds and try again.
  3322.             //        Will succeed when the user turns the printer on.
  3323.             //
  3324.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kDelayGetCapability", 0);
  3325.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3326.             
  3327.             pPrinterPB->pb.usbBuffer = 0;
  3328.             pPrinterPB->pb.usbActCount = 0;
  3329.             pPrinterPB->pb.usbReqCount = kUSS720MillisecondDelay;
  3330.             pPrinterPB->pb.usbFlags = kUSBTaskTimeFlag;
  3331.             
  3332.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3333.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3334.             pPrinterPB->delayInProgress = true;
  3335.             err = USBDelay(&pPrinterPB->pb);
  3336.             if(immediateError(err))
  3337.             {
  3338.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kDelayGetCapability - immediate error", 0);
  3339.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3340.             }
  3341.             break;
  3342.             
  3343.         case kAllocateCapabilityMem:
  3344.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kAllocateCapabilityMem", 0);
  3345.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3346.             length = *(UInt16*)(pPrinterPB->capability);
  3347.             pPrinterPB->pb.usbBuffer = 0;
  3348.             pPrinterPB->pb.usbActCount = 0;
  3349.             pPrinterPB->pb.usbReqCount = length;
  3350.             pPrinterPB->pb.usbFlags = 0;
  3351.             
  3352.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3353.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3354.             err = USBAllocMem(&pPrinterPB->pb);
  3355.             if(immediateError(err))
  3356.             {
  3357.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kAllocateCapabilityMem - immediate error", 0);
  3358.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3359.             }
  3360.             break;
  3361.         
  3362.         case kGetFullCapabilityString:
  3363.             //
  3364.             // the capability string was too long to fit in the statically allocated space
  3365.             // need to release this memory when we finalize our driver
  3366.             //
  3367.  
  3368.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetFullCapabilityString", 0);
  3369.             length = *(UInt16*)(pPrinterPB->capability);
  3370.             if ( pPrinterPB->pCapabilityString )
  3371.                 GetCapability( pPrinterPB, pPrinterPB->pCapabilityString, length );
  3372.             else
  3373.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"Can't allocate capability memory", 0);
  3374.             break;
  3375.             
  3376.         case kGetInterface:
  3377.             // failsafe check that we've got the right setup
  3378.             //    it's possible the device didn't respond to our SetInterface
  3379.             GetInterface( &pPrinterPB->pb, &pPrinterPB->whichAltInterface );
  3380.             break;
  3381.  
  3382.         case kFindBulkOutPipe:
  3383.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkOutPipe", 0);
  3384.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3385.             
  3386.             pPrinterPB->pb.usbBuffer = 0;
  3387.             pPrinterPB->pb.usbActCount = 0;
  3388.             pPrinterPB->pb.usbReqCount = 0;
  3389.             pPrinterPB->pb.usbFlags = kUSBOut;
  3390.             pPrinterPB->pb.usbClassType = kUSBBulk;
  3391.             
  3392.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3393.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3394.             err = USBFindNextPipe( &pPrinterPB->pb );
  3395.             if (immediateError(err))
  3396.             {
  3397.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"kFindBulkOutPipe - immediate error", err);
  3398.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3399.             }
  3400.             break;
  3401.             
  3402.         case kFindBulkInPipe:    
  3403.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkInPipe", 0);
  3404.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3405.             
  3406.             pPrinterPB->pb.usbBuffer = 0;
  3407.             pPrinterPB->pb.usbActCount = 0;
  3408.             pPrinterPB->pb.usbReqCount = 0;
  3409.             pPrinterPB->pb.usbFlags = kUSBIn;
  3410.             pPrinterPB->pb.usbClassType = kUSBBulk;
  3411.             
  3412.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3413.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3414.             err = USBFindNextPipe( &pPrinterPB->pb );
  3415.             if (immediateError(err))
  3416.             {
  3417.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"kFindBulkInPipe - immediate error", err);
  3418.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3419.             }
  3420.             break;
  3421.             
  3422.         case kTaskTimeRequired:
  3423.             MyUSBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired", 0);
  3424.              // to stress test usb bus, fallthrough to kGetCentronicsStatus 
  3425.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3426.             
  3427.             pPrinterPB->pb.usbBuffer = 0;
  3428.             pPrinterPB->pb.usbActCount = 0;
  3429.             pPrinterPB->pb.usbReqCount = kUSBNoDelay;
  3430.             pPrinterPB->pb.usbFlags = kUSBTaskTimeFlag;
  3431.             
  3432.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3433.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3434.             pPrinterPB->delayInProgress = true;
  3435.             err = USBDelay(&pPrinterPB->pb);
  3436.             if(immediateError(err))
  3437.             {
  3438.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kTaskTimeRequired - immediate error", 0);
  3439.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3440.             }
  3441.             break;
  3442.  
  3443.         case kGetCentronicsStatus:
  3444.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3445.  
  3446.             CentronicsStatus( &pPrinterPB->pb,  &pPrinterPB->centronics.b, pPrinterPB->interfaceNumber );
  3447.             
  3448.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3449.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3450.             err = USBDeviceRequest(&pPrinterPB->pb);
  3451.             if(immediateError(err))
  3452.             {
  3453.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kGetCentronicsStatus Immediate error", 0);
  3454.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3455.             }
  3456.             break;
  3457.             
  3458.         case kDelayGetCentronicsStatus:
  3459.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3460.  
  3461.             pPrinterPB->pb.usbBuffer = 0;
  3462.             pPrinterPB->pb.usbActCount = 0;
  3463.             pPrinterPB->pb.usbReqCount = kUSS720StatusMSDelay;
  3464.             
  3465.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3466.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3467.             pPrinterPB->delayInProgress = true;
  3468.             err = USBDelay(&pPrinterPB->pb);
  3469.             if(immediateError(err))
  3470.             {
  3471.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kDelayGetCentronicsStatus - immediate error", 0);
  3472.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3473.             }
  3474.             break;
  3475.             
  3476.         default:
  3477.             USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName"InitiateTransaction - unknown state", pPrinterPB->pb.usbRefcon);
  3478.             pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3479.             break;
  3480.     }
  3481.     
  3482.     if (pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  3483.     {
  3484.         pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;
  3485.         pPrinterPB->pb.usbRefcon &= ~kTransactionPending;
  3486.     }
  3487. }
  3488.  
  3489.  
  3490. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3491.     Name:        PrintDriverEntry
  3492.  
  3493.     Input Parameters:    
  3494.         
  3495.     Output Parameters:
  3496.         
  3497.     Description:
  3498.         This is where the system instantiates a USB printing device.
  3499.  
  3500.         We need to install drivers in the MacOS unitTable, and a reference
  3501.         in the name registry.
  3502.         
  3503.         But the information we need to do this is only available after some 
  3504.         USB transactions have completed. So we initiate here a series of asynchronous
  3505.         USB operations to get that information (by calling the first 
  3506.  
  3507.  
  3508.  
  3509.  
  3510.  
  3511. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3512. void 
  3513. PrintDriverEntry(
  3514.     USBDeviceRef                    deviceRef,
  3515.     USBDeviceDescriptorPtr            pDeviceDesc,
  3516.     USBInterfaceDescriptorPtr        pInterfaceDesc,
  3517.     UInt32                            interfaceNumber
  3518.     )
  3519. {
  3520.     static Boolean        beenThereDoneThat = false;
  3521.     OSStatus                err;
  3522.     
  3523.  
  3524.     RoutineDescriptor qw = BUILD_ROUTINE_DESCRIPTOR( uppQueueUSBWriteProcInfo, QueueWrite);
  3525.     RoutineDescriptor qr = BUILD_ROUTINE_DESCRIPTOR( uppQueueUSBReadProcInfo, QueueRead);
  3526.     RoutineDescriptor qa = BUILD_ROUTINE_DESCRIPTOR( uppAbortProcInfo, Abort);
  3527.     RoutineDescriptor qs = BUILD_ROUTINE_DESCRIPTOR( uppControlStatusProcInfo, ControlStatusRequests );
  3528.     
  3529.     if( !beenThereDoneThat)
  3530.     {
  3531.         printerClassRecord.terminating = false;
  3532.         printerClassRecord.printerRegistered = false;
  3533.         beenThereDoneThat = true;
  3534.         
  3535.         //DebugStr("\pIn Printer Driver Entry");
  3536.         MyUSBExpertStatusLevel(kNormalStatusLevel, deviceRef, kPStrPrinterDriverName"Starting USB Printer Driver", 0);
  3537.         
  3538.         printerClassRecord.deviceDescriptor = *pDeviceDesc;    /* keep a copy of the device descriptor */
  3539.         printerClassRecord.pInterfaceDescriptor = pInterfaceDesc;
  3540.         printerClassRecord.interfaceNumber = interfaceNumber;
  3541.         
  3542.         printerClassRecord.deviceRef = deviceRef;
  3543.         printerClassRecord.interfaceRef = deviceRef;
  3544.         
  3545.         printerClassRecord.transDepth = 0;            /* init Delay Callback Depth */
  3546.     
  3547.         printerClassRecord.inRefNum =  -1;            /* initially no DRVRs added to UnitTable */
  3548.         printerClassRecord.outRefNum =  -1;    
  3549.         err = LoadResources( &printerClassRecord );
  3550.         if ( err != noErr )  
  3551.             USBExpertFatalError( deviceRef, err, kPStrPrinterDriverName"LoadResources failed", 0);
  3552.         //
  3553.         //    routines to write and read to the device must be called by 68K DRVR
  3554.         //        so we use mixed-mode manager to dispatch between PPC and 68K
  3555.         //
  3556.         printerClassRecord.qwrite = (QueueUSBWriteUPP) &printerClassRecord.qwriteRD;
  3557.         printerClassRecord.qwriteRD = qw;
  3558.     
  3559.         printerClassRecord.qread = (QueueUSBReadUPP) &printerClassRecord.qreadRD;
  3560.         printerClassRecord.qreadRD = qr;    
  3561.         
  3562.         printerClassRecord.qstatus = (ControlStatusUPP) &printerClassRecord.qstatusRD;
  3563.         printerClassRecord.qstatusRD = qs;
  3564.  
  3565.         printerClassRecord.qabort = (AbortUPP) &printerClassRecord.qabortRD;
  3566.         printerClassRecord.qabortRD = qa;
  3567.  
  3568.         printerClassRecord.r = (QueueUSBReadUPP) QueueRead;
  3569.         printerClassRecord.w = (QueueUSBWriteUPP) QueueWrite;
  3570.         printerClassRecord.s = (ControlStatusUPP) ControlStatusRequests;
  3571.         printerClassRecord.a = (AbortUPP) Abort;
  3572.    
  3573.         SetNullUSBParamBlock( deviceRef, &printerClassRecord.pb );
  3574.         SetNullUSBParamBlock( 0, &printerClassRecord.in );        // fill in pipe ref later
  3575.         SetNullUSBParamBlock( 0, &printerClassRecord.out );    // fill in pipe ref later
  3576.         
  3577.         CStrCopy((char *)printerClassRecord.name, "");
  3578.         CStrCopy((char *)printerClassRecord.model, "");
  3579.  
  3580. #if DOUBLE_BUFFER
  3581.         //
  3582.         // Assume 1. TRANSFER_SIZE is a power of 2
  3583.         //    Assume 2. malignedBuffer is allocated to be 3*TRANSFER_SIZE
  3584.         //
  3585.         printerClassRecord.pageWriteAlignedBufferSize = TRANSFER_SIZE;                            // should get this from VM
  3586.         printerClassRecord.pageWriteAlignedBuffer = printerClassRecord.malignedBuffer;
  3587.  
  3588.         // align it below the buffer, then bring it into the range of the buffer
  3589.         *((UInt32 *) &printerClassRecord.pageWriteAlignedBuffer) &= ~(printerClassRecord.pageWriteAlignedBufferSize - 1);    //assumption1
  3590.         *((UInt32 *) &printerClassRecord.pageWriteAlignedBuffer) += printerClassRecord.pageWriteAlignedBufferSize;            //assumption2
  3591.  
  3592.         printerClassRecord.pageReadAlignedBufferSize = TRANSFER_SIZE;
  3593.         printerClassRecord.pageReadAlignedBuffer = printerClassRecord.pageWriteAlignedBuffer + TRANSFER_SIZE;
  3594.         
  3595. #endif
  3596.         printerClassRecord.printerConfigured = false;
  3597.     
  3598.         //
  3599.         //    Just to be thorough, lets hold our paramter blocks so that we won't page them at
  3600.         //        interrupt time. (We should be in the System heap and automatically held.)
  3601.         //
  3602.         HoldMemory( &printerClassRecord, sizeof(struct usbPrinterPBStruct) );
  3603.  
  3604.         CheckUSBVersion();
  3605.         
  3606.         //
  3607.         // Start out at first state
  3608.         //
  3609.         printerClassRecord.pCapabilityString = printerClassRecord.capability;
  3610.         printerClassRecord.pb.usbRefcon = kFindInterface_bidirectional;
  3611.         
  3612.         // don't start if we received a removal notification just as we're starting up
  3613.         if (printerClassRecord.terminating)
  3614.         {
  3615.             printerClassRecord.pb.usbCompletion    = (USBCompletion) NULL;
  3616.         }
  3617.         else
  3618.         {
  3619.             PrinterDeviceInitiateTransaction(&printerClassRecord.pb);
  3620.         }
  3621.     }
  3622. }
  3623.  
  3624. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3625.     Name:        PrinterRemovalNotification
  3626.  
  3627.     Input Parameters:    
  3628.         
  3629.     Output Parameters:
  3630.         
  3631.     Description:
  3632.         release any allocated storage
  3633.         remove DRVRs from the UnitTable
  3634.  
  3635.         One small complication happens when the USS-720 cable is used. It's possible
  3636.         that the user has the device plugged in, but the printer wasn't powered on.
  3637.         In this case, our state machine is still cycling between the states 
  3638.         kDelayGetCapability and kGetCapabilityString. If we terminate before the delay
  3639.         returns we'll crash the system. We monitor terminating to handle this
  3640.         
  3641.  
  3642.  
  3643.  
  3644.  
  3645.  
  3646.  
  3647.  
  3648.  
  3649.  
  3650.  
  3651. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3652. OSStatus
  3653. PrinterRemovalNotification( void )
  3654. {
  3655. static    Boolean    logfileclosed = false;
  3656. static    Boolean    aborted = false;
  3657. static    Boolean    deregistered = false;
  3658. static    Boolean    readpipeaborted = false;
  3659. static    Boolean    writepipeaborted = false;
  3660. static    Boolean    timedout = false;
  3661. OSStatus            result = noErr;
  3662. static unsigned long    tc = 0;
  3663.     //
  3664.     //    notify state machine not to continue
  3665.     //
  3666.     printerClassRecord.terminating = true;
  3667.     
  3668.     MyUSBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Driver removal notification received", 0);
  3669.     if (!logfileclosed)
  3670.     {
  3671.         MyUSBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Closing printer log file", 0);
  3672.         LOGGING( fclose( logfile ) );
  3673.         logfileclosed = true;
  3674.     }
  3675.     
  3676.     // if the printer was never registered, then don't try to deregister it
  3677.     if (!(printerClassRecord.printerRegistered))
  3678.         deregistered = true;
  3679.         
  3680.     if (!deregistered)    
  3681.     {
  3682.         //
  3683.         //    remove printer from the name registry
  3684.         //
  3685.         MyUSBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Removed printer entry from nameregistry", 0);
  3686.         DeregisterDevice( &printerClassRecord );
  3687.         deregistered = true;
  3688.     }
  3689.  
  3690.     // per the Mac OS USB DDK API Ref 
  3691.     // "If the device associated with this call [USBDelay] is unplugged and its driver removed while
  3692.     //  this function call is pending, the function will not complete."
  3693.     // therefore don't hang around if a delay is in progress
  3694.     if (( printerClassRecord.pb.usbCompletion != (USBCompletion) NULL ) && (!printerClassRecord.delayInProgress))
  3695.     {
  3696.         MyUSBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Waiting for configuration to complete", printerClassRecord.pb.usbRefcon);
  3697.         return (OSStatus) kUSBDeviceBusy;
  3698.     }
  3699.     
  3700.     // Abort any outstanding write requests
  3701.     if (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL ) && (!writepipeaborted))
  3702.     {
  3703.         MyUSBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Abort write pipe", printerClassRecord.writePipeRef);
  3704.         USBAbortPipeByReference( printerClassRecord.writePipeRef );
  3705.         writepipeaborted = true;
  3706.         return (OSStatus) kUSBDeviceBusy;
  3707.     }
  3708.     
  3709.     // Abort any outstanding read requests
  3710.     if (( printerClassRecord.in.usbCompletion != (USBCompletion) NULL ) && (!readpipeaborted))
  3711.     {
  3712.         MyUSBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Abort read pipe", printerClassRecord.readPipeRef );
  3713.         USBAbortPipeByReference( printerClassRecord.readPipeRef );
  3714.         readpipeaborted = true;
  3715.         return (OSStatus) kUSBDeviceBusy;
  3716.     }
  3717.     
  3718.     // Abort any outstanding transactions
  3719.     if (!aborted)
  3720.     {
  3721.         MyUSBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Call Abort()", 0);
  3722.         Abort( 0, &printerClassRecord );
  3723.         aborted = true;
  3724.     }
  3725.  
  3726.     // wait up to ten seconds for the read & write routines to complete.  When they do, the completion procptrs will be NULL'd
  3727.     if (tc == 0)
  3728.         tc = TickCount() + 10*60;
  3729.         
  3730.     if ( TickCount() >= tc )
  3731.         timedout = true;
  3732.         
  3733.     if (( TickCount() < tc ) &&
  3734.          (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL) ||
  3735.           ( printerClassRecord.in.usbCompletion != (USBCompletion) NULL )))
  3736.     {
  3737.         return (OSStatus) kUSBDeviceBusy;
  3738.     }
  3739.     
  3740.     // Put the appropriate timeout message in the log
  3741.     if ( timedout )
  3742.     {
  3743.         MyUSBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"took longer than 10 seconds for read/write pipes to complete", 0);
  3744.     }
  3745.     else
  3746.     {
  3747.         MyUSBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Pipes closed normally", 0);
  3748.     }
  3749.     
  3750.     if (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL) ||
  3751.           ( printerClassRecord.in.usbCompletion != (USBCompletion) NULL ))
  3752.     {
  3753.         MyUSBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Completion procs are not nil!!", 0);
  3754.     }
  3755.     
  3756.     // remove our unit table drivers
  3757.     if (printerClassRecord.outRefNum != -1 )
  3758.     {
  3759.         TradRemoveDriver( printerClassRecord.outRefNum, false );
  3760.         printerClassRecord.outRefNum = -1;
  3761.     }
  3762.     
  3763.     if (printerClassRecord.inRefNum != -1 )
  3764.     {
  3765.         TradRemoveDriver( printerClassRecord.inRefNum, false );
  3766.         printerClassRecord.inRefNum = -1;
  3767.     }
  3768.  
  3769.     //
  3770.     //    release any allocated storage
  3771.     //
  3772.     if ( printerClassRecord.pCapabilityString != printerClassRecord.capability )
  3773.     {
  3774.         MyUSBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Deallocated capability string memory", 0);
  3775.         printerClassRecord.pb.usbReference = printerClassRecord.deviceRef;             
  3776.         printerClassRecord.pb.usbFlags = 0;             
  3777.         printerClassRecord.pb.usbRefcon = kDeallocateCapbilityString;             
  3778.         printerClassRecord.pb.usbBuffer = printerClassRecord.pCapabilityString;        
  3779.         printerClassRecord.pb.usbCompletion = (USBCompletion)kUSBNoCallBack;
  3780.         printerClassRecord.delayInProgress = true;        // this prevents the control pipe completion procptr from being checked
  3781.         USBDeallocMem(&printerClassRecord.pb);
  3782.         
  3783.         printerClassRecord.pCapabilityString = printerClassRecord.capability;
  3784.         return (OSStatus) kUSBDeviceBusy;
  3785.     }
  3786.  
  3787.     //
  3788.     //    don't need to hang on to param blocks after we've gone away
  3789.     //
  3790.     UnholdMemory( &printerClassRecord, sizeof(struct usbPrinterPBStruct) );
  3791.  
  3792.     MyUSBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Ready for removal", 0);
  3793.     return kUSBNoErr;
  3794. }
  3795.  
  3796. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3797.     Name:        CFMInitialization
  3798.  
  3799.     Input Parameters:    
  3800.         initBlock
  3801.         
  3802.     Output Parameters:
  3803.         printerClassDriverFileSpec        set global
  3804.         
  3805.     Description:
  3806.         We use the code fragment initialization to get our filespec which 
  3807.         LoadResources will use to open our resource fork.
  3808.         
  3809.         A peculiarity of the USB 1.0 implementation is that does not lock the
  3810.         driver into physical memory. As a result a driver which does not call
  3811.         SetDriverClosureMemory on it's fragment will likely be paged in during
  3812.         interrupt time and a double bus-fault will occur. The solution for this
  3813.         is to have the USB Expert call SetDriverClosureMemory in a future release
  3814.         of the USB stack. In the meantime, we call it on ourselves to lock us into
  3815.         physical memory. When the USB stack is revved, one call to SetDriverClosureMemory
  3816.         (either this one or the Expert's) will be treated as a NOP.
  3817.  
  3818.  
  3819.  
  3820.  
  3821. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3822. OSErr
  3823. CFMInitialization( CFragInitBlock *initBlock )
  3824. {
  3825.     //
  3826.     //    get a reference to our file so that we can open up the resource fork later on
  3827.     //
  3828.     if ( CFragHasFileLocation( initBlock->fragLocator.where ) )
  3829.         printerClassDriverFileSpec = *(initBlock->fragLocator.u.onDisk.fileSpec);
  3830.  
  3831.     return noErr;
  3832.  
  3833. }
  3834.  
  3835. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3836.     Name:        MyUSBExpertStatusLevel
  3837.  
  3838.     Input Parameters:    
  3839.         level        value 1 - 5 of the status level for the message.  Refer to use in 
  3840.                         USBExpertStatusLevel call
  3841.         ref            device or interface reference associated with the message
  3842.         status        Pascal style string status message to log
  3843.         value        value to store along with status message.
  3844.         
  3845.     Output Parameters:
  3846.         returns a result of osstatus
  3847.         
  3848.     Description:
  3849.         MyUSBExpertStatusLevel checks the version of USB present and makes the 
  3850.         USBExpertStatusLevel call if USB 1.2 or later is present or uses the 
  3851.         USBExpertStatus call instead if USB 1.0 - 1.1 is present.  This requires 
  3852.         the one weak link with the USBServicesLib library file.
  3853.  
  3854.  
  3855. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3856. OSStatus MyUSBExpertStatusLevel(UInt32 level, USBDeviceRef ref, StringPtr status, UInt32 value)
  3857. {
  3858.     if (gUSBVersion < kUSBv12)
  3859.     {
  3860.         USBExpertStatus(ref, status, value);
  3861.     }
  3862.     else
  3863.     {
  3864.         USBExpertStatusLevel(level, ref, status, value);
  3865.     }
  3866. }
  3867.  
  3868.  
  3869.  
  3870. // eof
  3871.